What is difference between true, nil and false keywords in ruby?

true, nil and false are the keywords in Ruby. In which nil is a special keyword reserved to indicate the absence of value as name refer itself where true and false are the two boolean values, and they represent truth and falsehood, yes and no, on and off.

Each of these keywords evaluates to a special object.

true evaluates to an object that is a singleton instance of TrueClass. false evaluates to an object that is a singleton instances of FalseClass and nil evaluates to an object that is a are singleton instances of  NilClass. Note that there is no Boolean class in Ruby. TrueClass and FalseClass both have Object as their superclass.

If you want to check whether a value is nil, you can simply compare it to nil, or use the method nil?:

o == nil   # Is o nil?
o.nil?     # Another way to test

Note that true, false, and nil refer to objects, not numbers. false and nil are not the same thing as 0, andtrue is not the same thing as 1. When Ruby requires a Boolean value, nil behaves like false, and any value other than nil or false behaves like true.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.