Reputation: 6384
I had thought that Object
is an ancestor of all classes, but I tried something which made me confused.
Object.superclass # => BasicObject
Object.superclass.superclass # => nil
Object.superclass.superclass.superclass # => undefined method error since nil is not a class
Object.superclass.superclass.class # => Nilclass
Object.superclass.superclass.class.superclass # => Object
Except for nil
, everything has a superclass, and nil
is an instance of NilClass
, so it cannot have super class method. How one can get Object
as superclass of Object
?
Upvotes: 0
Views: 144
Reputation: 118271
superclass
is a method of Class
. Now NilClass
inherits from Object
. But the class Object
have no chance to inherit the class Class
methods.
See below from the Documentaion
Classes, modules, and objects are interrelated. In the diagram that follows, the vertical arrows represent inheritance,
and the parentheses meta-classes. All metaclasses are instances of the class `Class'.
+---------+ +-...
| | |
BasicObject-----|-->(BasicObject)-------|-...
^ | ^ |
| | | |
Object---------|----->(Object)---------|-...
^ | ^ |
| | | |
+-------+ | +--------+ |
| | | | | |
| Module-|---------|--->(Module)-|-...
| ^ | | ^ |
| | | | | |
| Class-|---------|---->(Class)-|-...
| ^ | | ^ |
| +---+ | +----+
| |
obj--->OtherClass---------->(OtherClass)-----------...
Yes that's correct as nil
being an object of NilClass
,which in turn inherits Object
which is on top of the class Class
. Thus Nilclass
couldn't inherit superclass
method.
Object.superclass.superclass #=> nil
nil.superclass #=> undefined method error since nil is not a class
Upvotes: 1
Reputation: 22969
From ruby-doc.org
BasicObject is the parent class of all classes in Ruby
The superclass of Object is BasicObject, and BasicObject does not have a superclass. The standard placeholder for non-existent things is nil, so BasicObject.superclass returns nil.
It so happens that nil is an instance of the class NilClass, which is a subclass of Object. This does not mean that NilClass is a superclass of BasicObject or that Object is a superclass of Object.
Upvotes: 5
Reputation: 174309
You don't get "Object as superclass of Object". What you get is "Object as superclass of Nilclass".
Upvotes: 4