In the eyes of ruby, 0 is true

Unlike many other languages, 0 isn’t qualified as false in an expression. For example :

a=0
if(a)
  #0 is true, so the code gets here
end

To Ruby, only 2 things are false : false and nil. I should rather say : An instance of FalseClass and an instance of NilClass. Everything else is true. 0 is a Fixnum instance and therefore is considered to be true.
How ruby can return false when you write if(3>5) then? The answer is quite simple : It is false because 3>5 (or should I say 3.>(5)) returns an instance of FalseClass.
I thought it was something important to note as this unusual definition of truth can cause some headaches to the unwary…

One thought on “In the eyes of ruby, 0 is true

Leave a Reply

Your email address will not be published. Required fields are marked *