Just as a plain-old
object can have a singleton class, class objects can also have their own singleton
classes. Those singleton classes, like all other classes, can have methods. Since the
singleton class is accessed through the klass pointer of its owner??™s class object,
the singleton class??™s instance methods are class methods of the singleton??™s owner.
The full set of data structures for the following code is shown in Figure 1-9:
class A
end
Class A inherits from Object. The A class object is of type Class. Class inherits from
Module, which inherits from Object. The methods stored in A??™s m_tbl are instance
methods of A. So what happens when we call a class method on A?
A.to_s # => "A"
The same method lookup rules apply, with A as the receiver. (Remember, A is a constant
that evaluates to A??™s class object.) First, Ruby follows A??™s klass pointer to Class. Class??™s
m_tbl is searched for a function named to_s. Finding none, Ruby follows Class??™s super
pointer to Module, where the to_s function is found (in native code, rb_mod_to_s).
Ruby Foundations | 15
This should not be a surprise. There is no magic here. Class methods are found in
the exact same way as instance methods??”the only difference is whether the receiver
is a class or an instance of a class.
Now that we know how class methods are looked up, it would seem that we could
define class methods on any class by defining instance methods on the Class object
(to insert them into Class??™s m_tbl).
Pages:
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40