views:

188

answers:

2

Hey. I would like to understand what "class << self" stands for in the next example.

module Utility
  class Options #:nodoc:
    class << self
      def parse(args)          
      end
    end
  end
end

Thx!

+3  A: 

this

module Utility
  class Options #:nodoc:
    class << self
      # we are inside Options's singleton class
      def parse(args)

      end
    end
  end
end

is equivalent to:

module Utility
  class Options #:nodoc:
    def Options.parse(args)

    end
  end
end

A couple examples to help you understand :

class A
  HELLO = 'world'
  def self.foo
    puts "class method A::foo, HELLO #{HELLO}"
  end

  def A.bar
    puts "class method A::bar, HELLO #{HELLO}"
  end

  class << self
    HELLO = 'universe'
    def zim
      puts "class method A::zim, HELLO #{HELLO}"
    end
  end

end
A.foo
A.bar
A.zim
puts "A::HELLO #{A::HELLO}"

# Output
# class method A::foo, HELLO world
# class method A::bar, HELLO world
# class method A::zim, HELLO universe
# A::HELLO world
macek
same as def self,parse(args) ?
xpepermint
@xpepermint, `self.parse(args)`, yes. (not `,`)
macek
+2  A: 

This is an eigenclass. This question's been asked before.

Frank Shearar
@Frank Shearar, out of fairness, I'm guessing the @xpepermint didn't realize this was an eigenclass :)
macek
Now official called singleton_class: http://github.com/ruby/ruby/blob/trunk/object.c#L166
Marc-André Lafortune
@Marc-Andre Lafortune, thanks for this :)
macek