From: Gavin Sinclair Date: 2002-12-02T10:44:04+09:00 Subject: Re: class << self (was Re: [FAQ] What do some of Ruby's symbols mean?) From: "Martin DeMello" > > def Array.newmethod1 > [define] > end > > or you can say > > class << Array > [define] > end These two are good. The first one is perfectly clear. The second one is quite nice. > or, if you are already *in* class Array and defining instance methods, > you can highilght the fact that you're working in the same conceptual > space by taking advantage of Ruby's setting 'self' to 'Array' when you say > 'class Array', and writing > > class Array > def instancemethod > [define] > end > > class << self > def classmethod > [define] > end > end > end > > There's no arcane magic going on here - self is an object of class > Class, and in this case it has the value Array. That, to me, is obfuscated. 'self' is generally understood as the current instance of the class. Therefore, it is only meaningful inside instance methods. In the "class << self" idiom, there is no instance method. 'self' may be defined, but it's not *meaningful* in the sense described above. There's a yawning gulf between syntax and semantics, and I suggest that it's taking advantage of an undocumented feature. My justification is that I have read a lot of Ruby documentation, and have become proficient at the language, but the rationale for "class << self" has never been impressed on me. In particular, the fact that 'self' has meaning immediately inside a class definition has not been impressed on me. That's why I wrote in an earier post that one shouldn't need to be mindful of Ruby's metaclass model when performing the perfectly normal OO practice of defining class (not instance) methods. The means of doing that should be more intuitive. Why would you say class Array class << self ... end end when you can say class Array class << Array ... end end ? The latter is much clearer to me. This applies to _why's (very good) example as well: class Win32API class << Win32API def def_api ... end end end BTW, I'm not trying to be difficult. I hope to read an equally robust reply in support of "class << self". Cheers, Gavin