On Thursday, September 11, 2003, 7:00:00 AM, Fredrik wrote:

> On Wed, Sep 10, 2003 at 05:06:28AM +0900, Mark J. Reed wrote:
>> 
>> Instead of using the class << self notation, you could do this:
>> 
>>       class TheClass
>>           def TheClass::foo
>> 
>> But that can get tedious when defining multiple class methods,
>> plus you run the risk of missing a change if you rename the class
>> later.

> I was just shown:

>     class TheClass
>         def self.foo

> This way you don't risk the missing a change when you rename the
> class. You still get the tedious typing though. :)

> However, what does 'class << self' really mean? Why is this one
> of the 'obvious' ways to define class methods? 

It's not necessarily obvious; it's an idiom, but it makes perfect
sense once you know, and it involves core Ruby concepts, so it is
worth knowing.

  s = "Hi"
  class << s
    def foo       # Singleton method on object s
      5
    end
  end
  s.foo           # -> 5

  s = String
  class << s
    def foo       # Singleton method on object String
      5
    end
  end
  s.foo           # -> 5
  String.foo      # -> 5

See http://www.rubygarden.org/ruby?ClassMethods for more info.

Gavin