Книга: Metaprogramming Ruby 2
Назад: Inside the Object Model
Дальше: What Happens When You Call a Method?

Quiz: Missing Lines

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:

images/chp1_classes_1.jpg
 
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:

You can use irb and the Ruby documentation to find out the answers.

Quiz Solution

Your enhanced version of the original diagram is in Figure 3, .

images/chp1_classes_2.jpg

Figure 3. Bill’s diagram, enhanced by you

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.

Назад: Inside the Object Model
Дальше: What Happens When You Call a Method?