w3resource

Ruby Basic Exercises: Check two integers and return whichever value is nearest to the value 10

Ruby Basic: Exercise-36 with Solution

Write a Ruby program to check two integers and return whichever value is nearest to the value 10, or return 0 if two integers are equal.

Ruby Basic Exercises: Check two integers and return whichever value is nearest to the value 10

Ruby Code:

def text_int(a, b)
    ma = (10-a).abs;
	mb = (10-b).abs;
	if (ma < mb)
		return a;
	end
	if (mb < ma)
		return b;
	end
	return 0;
end
print text_int(7, 14),"\n"
print text_int(6, 9),"\n"
print text_int(5, 5)

Output:

7
9
0

Flowchart:

Flowchart: Check two integers and return whichever value is nearest to the value 10

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to create a string using the first two characters (if present) of a given string if the first character is 'p' and second one is 's' otherwise return a blank string.
Next: Write a Ruby program to check two integer values and return true if they are both in the range 10..20 inclusive, or they are both in the range 20..30 inclusive.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.