From: Ben Lipton Date: 2007-12-22T11:59:35+09:00 Subject: Re: Singleton Method ------=_Part_1607_4435640.1198292380709 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline I think the answer is No, there isn't a difference, but it's something I've been wondering about. From http://blog.jayfields.com/2007/04/ruby-class-methods.html we have: "In fact, you can define a class method various ways, but the result is always an instance method on the singleton class." class Parser def self.self_process(script) # ... end def Parser.parser_process(script) # ... end class << self def singleton_process(script) # ... end end def self.singleton class << self; self; end end end Now, this is talking about class methods, not singleton methods on arbitrary objects, but I think the idea still applies because class methods are methods on a singleton, in this case the object Parser (which happens to be a Class). So, the second and the third examples are the ones you're asking about, because inside the "class Parser ... end", self is equal to Parser. So, he's doing def Parser.parser_process(script) end and class << Parser def singleton_process(script) end end just like your example. On Dec 21, 2007 8:24 PM, Joon You wrote: > 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 < > >> 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/. > > ------=_Part_1607_4435640.1198292380709--