Something confusing about Ruby: Object and Class
In Ruby, everything is an object, every object has a class, and all classes inherit from Object
. Three very simple statements.
Here’s where it gets complicated:
Classes are objects
If a class is an object, then it has to have a class. That class is Class
. Here’s an example
class Example; end #an empty class
Example.class # => Class
So, if Class
is a class, what is its class?
Class.class #=> Class
Ok, fine. What is Object
’s class?
Object.class #=> Class
No surprises there.
So far we’ve seen that Example
, Class
and Object
are all instances of the Class
class. That’s one part of OO - objects are instances of classes. In Ruby, where everything is an object, then even classes are instances of classes. And the the class of a class is Class
.
The other part of OO is inheritance. Classes inherit from other classes. I’ve already stated that everything inherits from Object
(either directly or indirectly). Let’s test that:
Example.superclass # => Object
Object.superclass # => nil (it's not turtles all the way down)
Class.superclass # => Module
Module.superclass # => Object
So, every class inherits from Object
except for Object
, which doesn’t inherit from anything.
Where does this lead then? Well, have a gander:
Object.instance_of? Class # => true
Class.is_a? Object # => true
Object
is an “instance” of Class
, but Class
“is” an Object
.
Conclusion
Ruby really does take this “everything is an object” thing seriously. Wow. And my brain hurts.