------ art_5262_10173760.1149104048691 Content-Type: text/plain; charset=WINDOWS-1252; format=flowed Content-Transfer-Encoding: quoted-printable Content-Disposition: inline On 5/31/06, Wes Gamble <weyus / att.net> wrote: > > I just ran into a seemingly weird problem until I discovered that the > method that I kept trying to call as an instance method was in fact a > class method. But of course, there isn't anything in the signature to > indicate that to me. Apparently, if you do this: > > class << self > def x > end > end > > then x is a class method, not an instance method. > > I'm having trouble finding a good explanation of this in the Pickaxe > book - is someone willing to give me the low down. > > This appears to be the common idiom for defining class methods and I'd > like to understand so I don't waste any more time. > > Thanks, > Wes > > -- > Posted via http://www.ruby-forum.com/. Here's an excerpt from Ruby for Rails by Black that does a good job of explaining it... <begin excerpt> Defining class methods with class << By far the most frequent use of the class << notation for entering a singleton method class is in connection with class method definitions. You'll see this quite often: class Ticket class << self def most_expensive(tickets) # etc. This code results in a class method Ticket.most_expensive. That method could also be defined like this (assuming this code comes at a point in the program where the Ticket class already exists): class << Ticket def most_expensive(tickets) # etc. Because self is Ticket inside the class Ticket definition body, class << self inside the body is the same as class << Ticket outside the body. (Technically, you could do class << Ticket even inside the body of class Ticket, but in practice you'll usually see class << self whenever the object whose singleton class needs opening is self.) The fact that class << self shows up frequently in connection with the crea- tion of class methods sometimes leads to the false impression that the class << notation can only be used to create class methods, or that the only expression you can legally put on the right is self. In fact, class << self inside a class definition block is just one case of the class << object notation. The technique is general: It puts you in a definition block for the singleton class of object, whatever object may be. That, in turn, means you're operating in a context where whatever you doÍØhatever you add to the classÍÑertains only to that one object. <end excerpt> HTH, Keith ------ art_5262_10173760.1149104048691--