From: Robert Klemme Date: 2004-08-11T06:06:14+09:00 Subject: Re: Singleton class methods "Gennady" schrieb im Newsbeitrag news:411926AD.1050408@tonesoft.com... > David A. Black wrote: > > Hi -- > > > > On Wed, 11 Aug 2004, Gennady wrote: > > > > > >>Kyle Putnam wrote: > >> > >>>Hello, > >>> > >>>It seems these two syntaxes accomplish the same thing, or are there > >>>differences? > >>> > >>> class Foo > >>> class << self > >>> def bar > >>> # ... > >>> end > >>> end > >>> end > >>> > >>>compared to... > >>> > >>> class Foo > >>> def Foo.bar > >>> # ... > >>> end > >>> end > >>> > >>>Cheers, > >>> Kyle > >>> > >>> > >> > >>Exactly the same from the functionality point of view (it differs in > >>implementation, though). I personally prefer the first form, as when it > >>comes to renaming a class, you can do it in one place. Also with this > >>form you can do other nice things such as defining class attribute > >>accessors with attr_reader, attr_writer or attr_accessor. > > > > > > One difference (I believe this was pointed out to me once by Guy > > Decoux, in response to the same question) is the scope of constants. > > If you open the new scope with << self, constants visible in method > > definitions will be those of that singleton class, rather than those > > of the original class. > > That's kind of what I meant. It seems like when you do > > class Foo > def self.bar > end > end > > method "bar" is added to the list of methods of the original class Foo. We have to be precise here to avoid confusion: did you mean as instance method? Then that's wrong. This method is added to the singleton class the same way in both approaches. $ irbs >> class Foo;end => nil >> class Foo >> class <> p( instance_methods.include?( "bar" ) ) >> end >> end false => nil >> class Foo >> def self.bar;end >> end => nil >> class Foo >> class <> p( instance_methods.include?( "bar" ) ) >> end >> end true => nil > On the other hand, for > > class Foo > class << self > def bar > end > end > end > > a singleton class is created for class object "Foo" and method "bar" is > defined in that singleton class, with all consequences. Hence, the > difference in implementation. > > It is how I see it. I may be completely wrong, though. I'm afraid you're wrong here. :-) A difference is though that you can define constants for the singleton class using the <