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.
Here’s an excerpt from Ruby for Rails by Black that does a good job of
explaining it…
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â??whatever you add to the classâ??pertains only to that one object.
Pickaxe2 in chapter 24 on page 362 (“Classes and Objects”) goes into
great extend explaining the “class << object” feature, with “class <<
self” in particular. With pictures and good examples. It may be a good
starting point.