3

I am a beginner at Ruby who is trying to understand its Object Model.

In IRB. I created a class called MyClass and started to check the Object Model like so:

    2.1.0p0 :013 > MyClass.class
     => Class
    2.1.0p0 :014 > MyClass.superclass
     => Object 
    2.1.0p0 :015 > Class.class
     => Class 
    2.1.0p0 :016 > Class.superclass
     => Module 
    2.1.0p0 :017 > Object.class
     => Class 
    2.1.0p0 :018 > Object.superclass
     => BasicObject 
    2.1.0p0 :019 > BasicObject.class
     => Class 
    2.1.0p0 :020 > BasicObject.superclass
     => nil

Question 1

Why do Myclass.superclass and Class.superclass are different when MyClass.class == Class.class returns true?

    2.1.0p0 :021 > Class.class == MyClass.class
     => true

In other words: Why are their superclasses different?

Question 2

Is this diagram accurate? Diagram's Link

Thank you in advance.

Roberto Decurnex
  • 2,514
  • 1
  • 19
  • 28
sargas
  • 5,820
  • 7
  • 50
  • 69
  • Look here http://stackoverflow.com/questions/19045195/understanding-ruby-class-and-ancestors-methods/19045339#19045339 to understand object model.. – Arup Rakshit Jan 16 '14 at 17:57
  • 2
    @ArupRakshit There is the best explanation on the subject so far. Thank you sir. – sargas Jan 16 '14 at 18:07
  • You can show these relationships easily with [Module#ancestors](http://ruby-doc.org/core-2.1.0/Module.html#method-i-ancestors): `MyClass.ancestors => [MyClass, Object, Kernel, BasicObject]`, `Class.ancestors => [Class, Module, Object, Kernel, BasicObject]`. – Cary Swoveland Jan 16 '14 at 18:21
  • I always found this really helpful: http://www.hokstad.com/ruby-object-model.html – Michael Kohl Jan 16 '14 at 20:01

1 Answers1

0

On Ruby classes al also objects, that's why the class of a class is actually Class.

That explains why:

Class.class   #=> Class
MyClass.class #=> Class
Class.class == MyClass.class #=> true

You are not calling class over an instance of each class but calling it over the classes itself. Is almost the same as:

"hey".class  #=> String
"jude".class #=> String
"hey".class == "jude".class #=> true

Here is what you were probably expecting at the beginning:

MyClass.new.class #=> MyClass
Class.new.class   #=> Class
MyClass.new.class == Class.new.class #=> false
Roberto Decurnex
  • 2,514
  • 1
  • 19
  • 28