D
dblack
Hi --
The starting-point of the whole thing is the principle that objects
can be individually extended. Two instances of MyClass, for example,
begin life with the same capabilities (methods), but during their
lives can diverge:
class MyClass
end
a = MyClass.new
b = MyClass.new
def a.x
end
def b.y
end
The singleton class mechanism is just a way to store those "extra"
methods. The methods written for a (namely, "x") go in a's singleton
class; those for b, in b's; etc. These classes are created
automatically when they are needed.
If you want to open a class definition block for an object's singleton
class, you use the class keyword, plus "<< obj". This special syntax
is necessary because singleton classes are anonymous. Other than
that, it's very much like doing "class C".
It's all very simple and elegant, isn't it?
David
Hmm.. Ok. But, with Ruby, you can still dynamically create subclasses
that aren't singletons and extend them as well as instanciate instances
of them, right? That would provide the flexibility I was referring to
above, but I suppose it would require typing quite a few more
characters. So do I understand correctly that Matz designed the whole
singleton creation mechanism ( << ) as a shorthand for doing more
long-winded dynamic creation/enhancing?
The starting-point of the whole thing is the principle that objects
can be individually extended. Two instances of MyClass, for example,
begin life with the same capabilities (methods), but during their
lives can diverge:
class MyClass
end
a = MyClass.new
b = MyClass.new
def a.x
end
def b.y
end
The singleton class mechanism is just a way to store those "extra"
methods. The methods written for a (namely, "x") go in a's singleton
class; those for b, in b's; etc. These classes are created
automatically when they are needed.
If you want to open a class definition block for an object's singleton
class, you use the class keyword, plus "<< obj". This special syntax
is necessary because singleton classes are anonymous. Other than
that, it's very much like doing "class C".
It's all very simple and elegant, isn't it?
David