Classes and Objects
Classes and objects are obviously central to Ruby, but at first sight
they can seem a little confusing. There seem to be a lot of concepts:
classes, objects, class objects, instance methods, class methods, and
singleton classes. In reality, however, Ruby has just a single
underlying class and object structure, which we'll discuss in this
chapter. In fact, the basic model is so simple, we can describe it in
a single paragraph.
A Ruby object has three components: a set of flags,
some instance variables, and an associated class. A Ruby class is an
object of class
, which contains all the object things plus a
list of methods and a reference to a superclass (which is itself
another class). All method calls in Ruby nominate a receiver (which is
, the current object).
Ruby finds the method to
invoke by looking at the list of methods in the receiver's class. If
it doesn't find the method there, it looks in the superclass, and then
in the superclass's
superclass, and so on. If the method cannot be found in the receiver's
class or any of its ancestors, Ruby invokes the method
on the original receiver.
And that's it---the entire explanation. On to the next chapter.
``But wait,'' you cry, ``I spent good money on this chapter. What
about all this other stuff---singleton classes, class methods, and so
on. How do they work?''