Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
Ruby Foundations | 5

The classClassinherits fromModule; every class is also a module. However, there is
an important distinction. Classes cannot be mixed in to other classes, and classes
cannot extend objects; only modules can.


Method Lookup


Method lookup in Ruby can be very confusing, but it is quite regular. The easiest
way to understand complicated situations is to visualize the data structures that
Ruby creates behind the scenes.


Every Ruby object* has a set of fields in memory:


klass
A pointer to the class object of this object. (It isklassinstead ofclassbecause
the latter is a reserved word in C++ and Ruby; if it were calledclass, Ruby
would compile with a C compiler but not with a C++ compiler. This deliberate
misspelling is used everywhere in Ruby.)


iv_tbl
“Instance Variable Table,” a hashtable containing the instance variables belong-
ing to this object.


flags
A bitfield of Boolean flags with some status information, such as the object’s
taint status, garbage collection mark bit, and whether the object is frozen.


Every Ruby class or module has the same fields, plus two more:


m_tbl
“Method Table,” a hashtable of this class or module’s instance methods.


super
A pointer to this class or module’s superclass.


These fields play a huge role in method lookup, and it is important that you under-
stand them. In particular, you should pay close attention to the difference between
theklass andsuper pointers of a class object.


The rules


The method lookup rules are very simple, but they depend on an understanding of
how Ruby’s data structures work. When a message is sent to an object,†the follow-
ing steps occur:



  • Except immediate objects (Fixnums, symbols,true,false, andnil); we’ll get to those later.
    † Ruby often co-opts Smalltalk’s message-passing terminology: when a method is called, it is said that one is
    sending a message. Thereceiver is the object that the message is sent to.

Free download pdf