Indyarocks
Indyarocks

Reputation: 653

superclass in ruby class is 'Object' but for 'Class' is 'Module

In Metaprogramming Ruby book, I can across the concept of superclass and class. Here is the reference image:

Object class superclass explained

As I understand: Class has an instance method defined superclass , which can be called by any new class defined (Here MyClass)

My question is:

The parent Class has superclass as Module but the object MyClass has superclass as Object . Why does superclass of Myclass is Object but not Module ? If it is by design, why is it designed this way?

Upvotes: 1

Views: 223

Answers (1)

Boris Stitnicky
Boris Stitnicky

Reputation: 12578

If you define a new class Foo in Ruby, then indeed, it is an instance of Class class, and Foo.class.superclass is Module as expected. But since you are asking not about the ancestors of Foo.class, but directly about the ancestors of Foo, then know that

class Foo
end

is the same as writing

class Foo < Object
end

In other words, a newly defined class will by default become a subclass of Object class, unless otherwise specified. Of course, you could manually define

class Bar < Module
end

in order to create an explicit subclass of Module class. Descendants of Module class have specific qualities and are of special use in Ruby. Note that class Class cannot be subclassed.

Upvotes: 2

Related Questions