Technology and Software

Called id for nil, which would mistakenly be 4

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

Ever got this misterious error message from Ruby on Rails?
It’s pretty clear that you tried to access to the method id of a nil object, but why should it mistakenly be 4???

Try this:

$ irb
irb(main):001:0> nil.id
(irb):1: warning: Object#id will be deprecated; use Object#object_id
=> 4
irb(main):002:0> nil.object_id
=> 4
irb(main):003:0>

So, the number 4 is explained: it’s the object id of the nil object.

And how about that error message, where does it come from?

Go to /usr/local/lib/ruby/gems/1.8/gems or whatever is the path to your rubygems installation, enter the activesupport directory,

open the lib/active_support/whiny_nil.rb file. There it is!

class NilClass
...
def id
raise RuntimeError, "Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id", caller
end

IMHO definitely not a cristal clear error message. It would be, without that “which would mistakenly be 4” part.

Standard