tags:

views:

614

answers:

4

This is has been bugging me for quite some time.

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

Why would nil.id be 4? (or nil.object_id if you want to be picky about deprecations)

+4  A: 

This post seems to have some information about how object_id works.

epochwolf
This is a useful link, I don't know why it vwas downvoted. +1
Keltia
Down voted probably because the person felt that this belonged in the text of my question. Which would be a valid point but downvoting without a comment doesn't get that across :)
epochwolf
+17  A: 

This is because nil is an object created when the language initializes, and that object's id happens to always be 4.

For more information about why the id happens to be 4, see this blog post.

dagvl
+1  A: 

It happens because the id of every object had to somehow be represented in the C Ruby interpreter. Numbers got mapped to (number*2)+1, truthiness got 0, falseness got 2 and nil had 4 left. It´s just a weird implementation issue or leaky abstraction. You shouldn't worry about it unless you want to write a Ruby interpreter.

LDomagala
A: 

I'd always assumed it was a cool easter egg: In Japan 4 is the number of death.

Andrew Peters