Ruby allows you to create a class tied to a particular object. In the
following example, we create two
String
objects. We then associate
an anonymous class with one of them,
overriding one of the methods in
the object's base class and adding a new method.
a = "hello"
|
b = a.dup
|
|
class <<a
|
def to_s
|
"The value is '#{self}'"
|
end
|
def twoTimes
|
self + self
|
end
|
end
|
|
a.to_s
|
� |
"The value is 'hello'"
|
a.twoTimes
|
� |
"hellohello"
|
b.to_s
|
� |
"hello"
|
This example uses the ``
class <<
obj'' notation, which
basically says ``build me a new class just for object
obj.'' We
could also have written it as:
a = "hello"
|
b = a.dup
|
def a.to_s
|
"The value is '#{self}'"
|
end
|
def a.twoTimes
|
self + self
|
end
|
|
a.to_s
|
� |
"The value is 'hello'"
|
a.twoTimes
|
� |
"hellohello"
|
b.to_s
|
� |
"hello"
|
The effect is the same in both cases: a class is added to the object
``
a
''. This gives us a strong hint about the Ruby implementation:
a singleton class is created and inserted as
a
's direct
class.
a
's original class,
String
, is made this singleton's
superclass. The before and after pictures are shown in Figure
19.3 on page 242.
Ruby performs a slight optimization with these singleton classes. If
an object's
klass
reference already points to a singleton class,
a new one will not be created. This means that the first of the two
method definitions in the previous example will create a singleton
class, but the second will simply add a method to it.