I was watching a metaprogramming video from PragProg, and Dave Thomas showed this snippet of code:
module Math
class << self
def is_even?(num)
(num & 1) == 0 # What exactly is going on here? Particularly (num & 1)
end
end
end
puts Math.is_even? 1 # => false
puts Math.is_even? 2 # => true
Now I understand what is going on here, but I don’t know what exactly is happening with the (num & 1) part of the Math.is_even? class method. I know it is a bitwise operation but that is about it. Can someone explain to me what is going with that line of code? Thanks.
&is a bitwise AND operator. Doing(num & 1)checks if the last bit (least significant bit) of the number is set. If it is set, the number is odd, and if it is not set, it is even.It is just a fast way to check if a number is even or odd.
You can see a list of the ruby bitwise operators here: http://www.techotopia.com/index.php/Ruby_Operators#Ruby_Bitwise_Operators