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 theClassobject
(to insert them into Class’sm_tbl). Indeed, this works:
class A; end
# from Module#to_s
A.to_s # => "A"
class Class
def to_s; "Class#to_s"; end
end
A.to_s # => "Class#to_s"
That is an interesting trick, but it is of very limited utility. Usually we want to define
unique class methods on each class. This is where singleton classes of class objects
are used. To open up a singleton class on a class, simply pass the class’s name as the
object to the singleton class notation:
class A; end
class B; end
class <<A
def to_s; "Class A"; end
end
A.to_s # => "Class A"
B.to_s # => "B"
The resulting data structures are shown in Figure 1-10. ClassB is omitted for brevity.
Figure 1-9. Full set of data structures for a single class
Object
Module
super
Class
super
A klass
super