Hi --

On Wed, 23 Nov 2005, Christophe Grandsire wrote:

> Selon "ako..." <akonsu / gmail.com>:
>
>>> @attributes = {}
>>>
>>> # Assumes the given object quacks on 'key'
>>> def @attributes.<<( keyed_obj )
>>>   (self[keyed_obj.key]||=[])<<keyed_obj
>>> end
>>>
>>> @attributes << a1
>>> @attributes << a2
>>> @attributes << a3
>>
>> this is something i have never seen. would you explain the 'def' line
>> above? is this the same as class << @attributes; def << ...; end ?
>>
>
> If I understand correctly you are asking whether:
>
> def @attributes.<<(obj)
>  ...
> end
>
> is the same as:
>
> class << @attributes
>  def <<(obj)
>    ...
>  end
> end
>
> (I rewrote them because the clash of << as syntax and << as method made it a bit
> difficult to read).
>
> The short answer is "yes". The long asnwer is that both are ways to add a
> singleton method to a particular object, @attributes in this case. The first
> one is just shorter and practical when you want to create just one singleton
> method. But it's mostly a matter of style.

There's also a (usually not too important) difference involving the
scope of constants.  The << version will see constants in the
singleton class, whereas the def obj.meth version won't:

   obj = Object.new

   A = 1

   class << obj
     A = 2
     def x
       puts A
     end
   end

   def obj.y
     puts A
   end

   obj.x         # 2
   obj.y         # 1


David

-- 
David A. Black
dblack / wobblini.net