Just out of curiosity, is there a difference between

def a.second
...
end

and

class << a

?

Gary Wright wrote:
> On Dec 21, 2007, at 6:51 PM, Ryan Lewis wrote:
> 
>> What's the difference between a regular method and a singleton method?
> 
>  From the perspective of a particular object, singleton methods are
> those methods that are defined within the singleton class of
> the object.
> 
> Regular methods are methods that are defined within the normal
> inheritance tree of the object's class.
> 
> Method lookup is done by first checking the singleton class of an
> object and if not found there by checking the normal inheritance tree.
> 
> By default objects don't have a singleton class.  The singleton class
> is created when it is referenced:
> 
> $ irb
>  >> a = [1,2,3]
> => [1, 2, 3]
>  >> a.second
> NoMethodError: undefined method `second' for [1, 2, 3]:Array
>          from (irb):2
>          from :0
>  >> class <<a
>  >>   def second
>  >>     self[1]
>  >>     end
>  >>   end
> => nil
>  >> a.second
> => 2
>  >> [4, 5, 6].second
> NoMethodError: undefined method `second' for [4, 5, 6]:Array
>          from (irb):9
>          from :0
>  >>
> 
> In this example, I opened up the singleton class associated
> with 'a' and defined a new method, second, that returns the
> second element of the array.  As you can see, this method
> is only available to that one particular array and not to
> all array's in general.
> 
> Gary Wright

-- 
Posted via http://www.ruby-forum.com/.