Monday, September 22, 2008

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

No comments: