Serjik
Serjik

Reputation: 10971

Why MyClass.class.superclass in Ruby is Module

I had a class named MyClass in ruby. When I check it in irb as

>class MyClass
>end

> MyClass.class.superclass

I get

 => Module 

I need to know the technical description of this output

Upvotes: 1

Views: 107

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187262

First, lets look at this code:

MyClass.class #=> Class

Funky. So a class, is actually an instance of the class named Class. Meaning these two lines are pretty similar:

class MyClass; end
MyClass = Class.new

And these are similar, too.

class MyClass; end;
myInstance = MyClass.new

myInstance = Class.new.new # I know this looks funky, but it works

So now we get to:

MyClass.class.superclass #=> Module

So the class named Class inherits from Module. This makes sense since a Class behaves just like a Module except that you can instantiate it, and it cannot be included.


Checkout the docs for Class and for Module for more info and how those two classes work.

Realizing that ruby is "turtles all the way down" is important. And a class object being an instance of class Class is one of the best examples of that, if you can get your head around it :)

Upvotes: 3

Related Questions