Rails类<<自

时间:2010-04-02 16:58:46

标签: ruby class

我想了解下一个例子中class << self代表什么。

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

2 个答案:

答案 0 :(得分:41)

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

      end
    end
  end
end

相当于:

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

    end
  end
end

有几个例子可以帮助您理解:

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

答案 1 :(得分:4)

这是一个本征类。这个问题是been asked before