Rails class << self

46

我希望了解下面这个例子中的class << self表示什么意思。

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

1
@xpepermint,你应该将“ruby”标签添加到这个问题中。 - maček
2个回答

53

这个

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

2
和 def self.parse(args) 一样吗? - xpepermint
4
@xpepermint,self.parse(args),是的。 - maček
这在当前版本的Ruby中是否仍然有效? - Beulah Akindele

4

这是一个特殊的类。这个问题之前已经被问过


@Frank Shearar,公平起见,我猜@xpepermint没有意识到这是一个特殊类(eigenclass) :) - maček
4
现在官方称之为 singleton_class:http://github.com/ruby/ruby/blob/trunk/object.c#L166 - Marc-André Lafortune

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接