class << self ...end - how does this create class methods?

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/195353

On Thu, 1 Jun 2006 04:18:18 +0900, Wes Gamble 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.

There are several different pieces which fit together:

1. Classes are themselves represented as objects.

class Foo
  # ...
end

p Foo.class # => Class

2. Methods can be defined on a per-object basis

foo = Object.new

def foo.blah
  puts "eek"
end

foo.blah # => eek

3. you can also define per-object methods this way:

foo = Object.new

class << foo
  def blah
     puts "eek"
  end
end

foo.blah # => eek

4. outside of methods, within a class … end block, self refers to the class

class Foo
  p self # => Foo
end

5. “class methods” are simply per-object methods defined on classes

class Foo
  class << self
    def blah
      puts "eek"
    end
  end
end

Foo.blah # => eek  

-mental

Similar Posts:

Post a Comment

Your email is never published nor shared.