Question

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)

Was it helpful?

Solution

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.

OTHER TIPS

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

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.

If you are trying this in irb you are getting 4

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

In ruby Japanese people set on nil methods call it returns 4 it's language standard that they set 4 as "Dangerous" OR "Death"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow