Ruby even? Method

Ruby even? Function with Examples

Ruby even? method is an integer class function that is used to check if an integer number is even or not. Applying this method to any other data type including double or float will raise an error.

Syntaxnum.even?
Where num is the integer data type variable.
ParametersThis method does not accept any parameters.
Return valueReturn a boolean value true or false depending on the number. If the number is even then it returns true otherwise false.

Example Program

num1 = 23
num2 = 22
num3 = -41
num4 = -14

puts num1.even?
puts num2.even?
puts num3.even?
puts num4.even?

Output

false
true
false
true

Business Logic

You can check the number even or odd in any place in your program directly for handling conditions. Consider the following example:

print "Enter a number to divide by 2: "
num = gets.to_i

if num.even?
    puts "#{num} / 2 = #{num/2}"
else
    puts "#{num} is not an even number."
end

Output

Sample InputSample Output
1010 / 2 = 5
1515 is not an even number.
Posted in