Why the id of nil is 4 in Ruby

Neeraj Singh

Neeraj Singh

June 23, 2008

Following code was tested with ruby 1.8.7 and Rails 2.3 .

While developing rails application you have must seen this


Called id for nil, which would mistakenly be 4 — if you really
wanted the id of nil, use object_id

We all know that this message is added by Rails and it is called whiny nil . If you open your config/development.rb file you will see

# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true

Simply stated it means that if the application happens to invoke id on a nil object then throw an error. Rails assumes that under no circumstance a developer wants to find id of a nil object. So this must be an error case and Rails throws an exception.

The question I have is why 4. Why Matz chose the id of nil to be 4. This awesome presentation on 'Ruby Internals' has the answer.

In short Matz decided to have all the odd numbers reserved for numerical values. Check this out.

> irb
>> 0.id
(irb):1: warning: Object#id will be deprecated; use Object#object_id
=> 1
>> 1.id
(irb):2: warning: Object#id will be deprecated; use Object#object_id
=> 3
>> 2.id
(irb):3: warning: Object#id will be deprecated; use Object#object_id
=> 5
>> 3.id
(irb):4: warning: Object#id will be deprecated; use Object#object_id
=> 7

Id 1,3,5 and 7 are taken by 0,1,2 and 3.

Now we are left with the id 0,2,4 and higher values.

> irb
> FALSE.id
(irb):5: warning: Object#id will be deprecated; use Object#object_id
=> 0
>> TRUE.id
(irb):6: warning: Object#id will be deprecated; use Object#object_id
=> 2

FALSE had the id 0 and TRUE has the id 2.

Now the next available id left is 4 and that is taken by NIL.

> irb
>> NIL.id
(irb):7: warning: Object#id will be deprecated; use Object#object_id
=> 4

We won't even be discussing this issue once 1.9 comes out where we will have to use object_id and then this won't be an issue.

You can follow more discussion about this article at Hacker news .

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.