Is there any difference between using self in a method name, and not
using it?
For example, I've seen a lot something like
class Foo
def self.bar
...
end
end
Is this the same thing as
class Foo
def bar
...
end
end
def self.bar is just a special case of:
def some_object.some_method
i.e., defining a singleton method on an object (a method that exists
only in the method look-up for that particular object, not for other
objects of its class). Actually it's not even a special case; it's
just using the current value of self as the object on which to define
the method.
At the top level of a class definition block, self is the class object
-- in this case, Foo. A singleton method defined on a class object
(such as Foo.bar) is usually referred to as a class method. In
addition, class methods are special-cased a bit, in comparison with
other singleton methods... but that's Lesson Two
Notice that you can't use the same method name statically and
as instance method in Java, whereas you can use the same name
for the class method and the instance method in Ruby.
Yes, except in the second you're actually opening up the virtual class
to work on it directly whereas in the first example you're defining
the method using an absolute name.
It's easy to see this as a pattern though without understanding the
background, which, hopefully, a brief example will rectify:
class << Fixnum
def x; "y"; end
end
puts Fixnum.x # => "y"
puts 10.x # ERROR
Note that you can dig into virtual classes at any time, not just
within the capacity of a class you're currently defining
So.. when you see class << self within the definition of another
class, then it's the equivalent of class << ClassName, and merely
using the "self" to provide the current class rather than naming it
explicitly.
Cheers,
Peter Cooper
···
On 6/12/07, Bertram Scharpf <lists@bertram-scharpf.de> wrote: