Hi --

On Sat, 10 Dec 2005, jonathan <zjll9 / imail.etsu.edu> <zjll9 / imail.etsu.edu> <zjll9 / imail.etsu.edu> wrote:

> transfire wrote:
>> Well, I think its basically because Matz used the class nothing more
>> then an easy way to implement ad hoc methods. It was the methods that
>> mattered to him, not the class --the class was just a vehicle. He's
>> talked about the possibility of not utilizing the class in the future.
>> I assume that means these methods would then just exit in a separate
>> underlying namespace of the class, as opposed to a separate class
>> altogether. Which may also be the reason he's allowed then name to
>> remain a bit amorphis and never provided a convenience method for
>> accessing it.
>
> 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

-- 
David A. Black
dblack / wobblini.net

"Ruby for Rails", forthcoming from Manning Publications, April 2006!