Where you find your way around the Ruby object model.
Back in , Bill showed you how objects and classes are related. As an example, he used a snippet of code and this whiteboard diagram:
| class MyClass; end |
| obj1 = MyClass.new |
| obj2 = MyClass.new |
The diagram shows some of the connections between the program entities. Now it’s your turn to add more lines and boxes to the diagram and answer these questions:
What’s the class of Object?
What’s the superclass of Module?
What’s the class of Class?
Imagine that you execute this code:
| obj3 = MyClass.new |
| obj3.instance_variable_set("@x", 10) |
Can you add obj3 to the diagram?
You can use irb and the Ruby documentation to find out the answers.
Your enhanced version of the original diagram is in Figure 3, .
As you can easily check in irb, the superclass of Module is Object. You don’t even need irb to know what the class of Object is: because Object is a class, its class must be Class. This is true of all classes, meaning that the class of Class must be Class itself. Don’t you love self-referential logic?
Finally, calling instance_variable_set blesses obj3 with its own instance variable @x. If you find this concept surprising, remember that in a dynamic language such as Ruby, every object has its own list of instance variables, independent of other objects—even other objects of the same class.