malcoauri
malcoauri

Reputation: 12189

Class hierarchy in Ruby

I've just got deeper in Ruby hierarchy to understand it. For example,

class Test
end

t = Test.new

So, if I want to get class of t I need to get 'class' property:

t.class # 'Test'

If I want to get parent of Test class I should use 'superclass' method:

t.class.superclass # BasicObject

But also Test is an instance of Class class. So, if I execute the following thing:

t.class.class # Class

So, I don't understand the difference between 'superclass' and 'class.class'; why aren't Class superclass for Test? What does it mean? Doest Test inherit methods of Class or BasicObject or both ones? Please, explain this thigns to me. I came from Java and I didn't hear about this features before. Thanks.

Upvotes: 0

Views: 1012

Answers (3)

Max
Max

Reputation: 22325

Every object responds to class. It says what class the object is an instance of.

Only classes respond to superclass. It says what class the class is a subclass of.

Foo = Class.new # class Foo; end
foo = Foo.new

Foo.class # Class
foo.class # Foo

Bar = Class.new(Foo) # class Bar < Foo; end
Bar.class # Class
Bar.superclass # Foo

All classes are instances of Class. Ruby does not allow subclasses of Class.

Upvotes: 1

jan.zikan
jan.zikan

Reputation: 1316

All objects are descendents of class Object. Class is object too and it is an instance of Object, which can seem a little weird.

    class Test
    end

    Test.class # => Class
    Test.superclass # => Object
    Object.class # => Class
    Class.superclass # => Module
    Module.class # => Class
    Module.superclass # => Object
    Object.superclass # => BasicObject

All descendents of class Object inherit quite a lot of methods like clone, dup, freeze and many many other methods. On the other hand BasicObject will provide you almost no methods - it doesn't even provide you methods: methods and public_methods.

Upvotes: 0

Marek Lipka
Marek Lipka

Reputation: 51151

First of all, by default, implicit superclass of the class you define is Object, not BasicObject. Now, Test.superclass methods returns class that Test directly inherits from. While Test.class returns class that Test is instance of. Remember that classes in Ruby are also objects, all objects in Ruby belongs to some class.

Upvotes: 2

Related Questions