How to check if an integer is even in Ruby
Overview
In Ruby, the even? method is used to find if an integer is an even number.
Syntax
intValue.even?
Parameters
This method takes no parameters.
Return Value
It returns a boolean value true if the integer intValue is even. Otherwise, it returns false.
Example
# create some integersint1 = 45int2 = 4*3-3+5int3 = 4**3int4 = -5# check if even# and print resultsputs int1.even?puts int2.even?puts int3.even?puts int4.even?
Explanation
- Lines 2–5: We create integer values.
- Lines 9–12: We invoke the
even?method on the integer values and print the results to the console.