Monday, September 22, 2008

Three ways to invoke a method in ruby

1. object = Object.new
puts object.object_id
#=> 282660

2. puts object.send(:object_id)
#=> 282660

3. puts object.method(:object_id).call
#=> 282660

why in ruby nil.object_id is equal to 4 ?

A very good explanation found at http://www.joesniff.co.uk/ruby/rubyrails-interview-questions.html

The object_id method returns the identity of an object. Every object must have a unique id. Hence if two objects have the same object_id, they are the same object.

Ruby’s booleans and nil are objects, so they deserve to be treated like real objects just like the rest. So they too should have an object_id.

When allocating object ids we are restricted with what ids we can use as Fixnum uses the odd object_ids (well all those needed to reach the maximum Fixnum). It takes the odd ids as the least significant bit is always set to 1 to flag this as a Fixnum.

So starting at the sensible point of 0 this leaves us with the following order:

0 => False
1 => 0 (Fixnum)
2 => True
3 => 1 (Fixnum)
4 => Nil
5 => 2 (Fixnum)
6 => Undefined