Lessons learned from true, false and nil objects in ruby

Bookmark this on Digg
Bookmark this on Delicious
Share on Facebook
Post to Google Buzz
Bookmark this on Yahoo Bookmark
Share on FriendFeed
[`tweetmeme` not found]

Every expression in Ruby evaluates to an object and every object has a boolean value. The boolean values are always the same instance of the TrueClass and FalseClass classes and will therefore always have the same id. Most objects in Ruby will have a boolean value of true. Only two objects have a boolean value of false, these are the false object itself and the nil object.

 

2.1.0 :027 > true.class
 => TrueClass
2.1.0 :028 > false.class
 => FalseClass

 

2.1.0 :029 > p = TrueClass.new
NoMethodError: undefined method `new' for TrueClass:Class 
  from (irb):29 
  from /Users/gakshay/.rvm/rubies/ruby-2.1.0/bin/irb:11:in `<main>'
2.1.0 :030 > f = FlaseClass.new
NameError: uninitialized constant FlaseClass 
  from (irb):30 
  from /Users/gakshay/.rvm/rubies/ruby-2.1.0/bin/irb:11:in `<main>'

 

2.1.0 :052 > true.object_id
 => 20
2.1.0 :053 > false.object_id
 => 0

 

2.1.0 :031 > if :expresssion
2.1.0 :032?> puts "yeah, it's an object"
2.1.0 :033?> end
yeah, it's an object
 => nil

 

2.1.0 :034 > if 11
2.1.0 :035?> puts "Yeah, the boolean value of an integer object is true"
2.1.0 :036?> end
Yeah, the boolean value of an integer object is true
 => nil

 

2.1.0 :037 > if !false
2.1.0 :038?> puts "Yeah, boolean value of false has to be false"
2.1.0 :039?> end
Yeah, boolean value of false has to be false
 => nil

 

2.1.0 :040 > if nil
2.1.0 :041?> puts "Damn, nil can't be true"
2.1.0 :042?> else
2.1.0 :043 > puts "yeah, boolean value of nil object is false"
2.1.0 :044?> end
yeah, boolean value of nil object is false
 => nil
2.1.0 :045 > nil.class
 => NilClass
2.1.0 :046 > nil.object_id
 => 8

 

2.1.0 :047 > if def i_am_a_method; end
2.1.0 :048?> puts "can it be true"
2.1.0 :049?> else
2.1.0 :050 > puts "a method definition evaluates to FALSE"
2.1.0 :051?> end
can it be true

 

To re-iterate :

Every expression in Ruby evaluates to an object and every object has a boolean value. The boolean values are always the same instance of the TrueClass and FalseClass classes and will therefore always have the same id