I want to check if the number is even! I tried the following:
a = 4.0
a.is_a? Integer
=> false
a.even?
=> undefined method for Float
S
If you are unsure if your variable has anything after the decimal and would like to check before converting to integer to check odd/even, you could do something like this:
a = 4.6
b = 4.0
puts a%1==0 && a.to_i.even? #=> false
puts b%1==0 && a.to_i.even? #=> true
Additionally, if you want to create an even? method for the Float class:
class Float
def even?
self%1==0 && self.to_i.even?
end
end
a = 4.6
b = 4.0
a.even? #=> false
b.even? #=> true