From: "David A. Black" Date: 2008-03-15T05:09:49+09:00 Subject: Re: need for singleton_methods Hi -- On Sat, 15 Mar 2008, Chinna Karuppan wrote: > I have trying to learn about this class< class< anything which will help this case.I can very well do it directly on the > class ... > class Foo > def Foo.bar > end > end > > what is the advantage I get by using the class << self notation... > > class Foo > class< def bar > end > end > end > > This is all confusing .Can any body suggest a simple example with > tangible result to show the advantage.I am pretty sure more > people(nubies) will have this.... > > I have been doing my home work for the pass 2 days. I found that it is > helpful in inheritance as per the whytheluckystiff.com guy (why's > poignant guide)....I don't understand what is the need for even in that > case.If I define the method directly like this > > class Foo > def Foo.bar > end > end > > class Hoo < Foo > end > > I am still OK ...Hoo.bar will work... > Any body want to pitch thier thoughts.... The main thing that's going on here is that objects are getting the ability to grow on an individual basis, and that's a central principle of Ruby. The way they grow is through the acquisition of methods that other objects of their class don't have. The point of the singleton class is to provide a uniform interface to the various layers of behavior that make up the object. Whenever you want to add, override, or undefine methods, you can do it inside a class definition block -- either class C, or class << object. Also, keep in mind that (as per that last example) it's not just for class objects. It's a general mechanism for implementing per-object behavior. David -- Upcoming Rails training from David A. Black and Ruby Power and Light: ADVANCING WITH RAILS, April 14-17 2008, New York City CORE RAILS, June 24-27 2008, London (Skills Matter) See http://www.rubypal.com for details. Berlin dates coming soon!