0

The Class has the superclass Module, which has the superclass Object, which has the superclass BasicObject, which is an instance of Class. And Class is again a subclass of Module.

I'm really confused regarding this.(the above was gleaned from using the .class and .superclass methods on each of the above objects)

Can anyone explain to me what exactly is going on here?

  • What are you confused about? Your description above is correct. What you described correctly is exactly what is going on. – sawa Jul 30 '13 at 17:59
  • 1
    Also check out [Class SuperClass Paradox](http://stackoverflow.com/questions/10558504/can-someone-explain-the-class-superclass-class-superclass-paradox) and [Ruby Metaclass Confusion](http://stackoverflow.com/questions/10525053/ruby-metaclass-confusion). – coreyward Jul 30 '13 at 18:00
  • I'd recommend the ScreenCast series by the Pragmatic Programmers on The Ruby Object Model and Metaprogramming: http://pragprog.com/screencasts/v-dtrubyom/the-ruby-object-model-and-metaprogramming – Tilo Jul 30 '13 at 19:00

1 Answers1

0

The phrase "instance of" is a small but significant part of the mental gymnastics you need to do here.

That, and objects of type Class, and a class called Object.

If you can understand these, at least while repeating to yourself slowly, then you have got it:

  • Object.new creates an instance of class Object

  • Object is a reference to the class Object, which is itself an object of class Class

  • Class is a reference the class Class, which is also an object of class Class (!)

  • Class.new creates an instance of class Class.

    • This is part of what happens under the hood when you write class Foo
    • In fact Foo = Class.new( String ) is much the same as class Foo < String; end
  • The class hierarchy of Class, Module, Object is an implementation detail in Ruby. Almost all classes inherit from Object, so it is no real surprise that Class does so too.

The rest is just repeated use and experience.

It is worth noting something else going on here: The labels in the code you type are symbols/variable names, which are pointers to the underlying objects which have types and contain data. There is no requirement to use those labels directly, they are pretty much the same as any other Ruby variable:

o_klass = Object
o_instance = o_klass.new
o_instance.class
 => Object
Neil Slater
  • 26,512
  • 6
  • 76
  • 94