In the MRI implementation of gc.c I saw an object named undef
. What is that undef
object? What is its class? How can I access it? Is there any utility for it?
This is an educated guess on my part, maybe Matz will see this question at some point and give us a definitive answer, hopefully this will do in the meantime.
As you might know, ruby was somewhat influenced by perl at least early on (which is why we have variables like $@ and $_ etc.). Perl has an undef
keyword/function (e.g. if you declare a variable without initialising - its value is undefined). I would say, that at some time in the past Ruby was also meant to have something similar (i.e. variables would be able to have an undefined value). How do we know this? By the context in which it is found.
As you can see, that comment describes how the object_id
of the various Ruby objects is derived. Some details on that can be found here. But, in essence we know the following:
false.object_id == 0
true.object_id == 2
nil.object_id == 4
This is what the comment suggests and this is indeed the case, you can crack open an irb
session and try it out for yourself. It looks like undef
was meant to have an object_id
of 6.
Now, undef
is indeed a reserved word in Ruby, but it is not a special object like nil
, false
and true
, it is - as we know - a keyword used to undefine a method.
So, to answer your question, there is no undef
object, it has no class and you can't access it. The purpose that undef
was meant to serve is instead being served by the nil
object in the Ruby that we know today. But, it has remained in the code as a legacy of times gone by, for the more curious of us to find and puzzle over.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With