Home > Programming > Something confusing about Ruby: Object and Class

Something confusing about Ruby: Object and Class

November 8th, 2010

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.


Ruby really does take this “everything is an object” thing seriously. Wow. And my brain hurts.

Categories: Programming Tags: ,
  1. March 1st, 2014 at 20:09 | #1

    Hello there, I love coding with Ruby. Havent been using it very long but learnt a good deal from websites throughout the net. Fortunately, your web site has assisted mme heaps, and finally I say thanks a lot foor the crystal-clear explanations and really easy to follow ideas on this web-site.

Comments are closed.