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

(Tuis.) #1
Ruby Foundations | 7

The next-simplest case is inheritance from one class. Class inheritance simply fol-
lows thesuper pointers. For example, we will create aB class that descends fromA:


class B < A
end

The resulting data structures are shown in Figure 1-2.


Thesuperkeyword always delegates along the method lookup chain, as in the fol-
lowing example:


class B
def initialize
logger.info "Creating B object"
super
end
end

The call tosuperininitializewill follow the standard method lookup chain, begin-
ning withA#initialize.


Class instantiation


Now we get a chance to see how method lookup is performed. We first create an
instance of classB:


obj = B.new

This creates a new object, and sets its klass pointer to B’s class object (see
Figure 1-3).


Figure 1-2. One level of inheritance


Object

A

super

B

super
Free download pdf