Check that Object constant is defined
Module.const_defined?('Object')
#=> true
Remove the constant
Object.send(:remove_const, 'Object')
#=> Object
Check, that Object constant is removed
Module.const_defined?('Object')
#=> false
Now, how do the following examples return the Object constant if it is removed? :)
String.superclass
#=> Object
new_object = String.superclass.new
#=> #<Object:0x00007fdc18382858>
new_object.class
#=> Object
They don't. They can't. Constants aren't objects in Ruby, therefore, they cannot possibly return the
::Objectconstant.They can, however, return an object which responds to
inspectwith the string'Object'. An object, which happens to be the same object which used to be referenced by the now-removed::Objectconstant.Removing the constant removes the constant. Nothing more. In particular, it does not delete the object that is referenced by the constant. IFF that constant was the only reference to that object, THEN that object will now be eligible for garbage collection. But that is not the case here: the
::Objectconstant is not the only reference to theObjectclass, since every subclass of theObjectclass has a reference to theObjectclass in itssuperclasspointer and every instance of theObjectclass has a reference to theObjectclass in itsclasspointer. Plus, internal data structures of the execution engine may or may not have references to theObjectclass.Therefore, the
Objectclass will pretty much never get garbage collected, and you will always have some reference to it, through which you can access it, e.g.''.class.superclasswill give you access to theObjectclass regardless of whether or not the::Objectconstant still exists.In short: you are confusing the constant
::Objectwith the object that is referenced by this constant. This is a common beginner mistake. However, the distinction between the name of a thing and the thing itself is fundamental in almost all programming languages.