模块类 << self 常量

4

有没有我的L常量?

module M
  class Z
    class << self
      L = "foo"
    end
  end
end

=> M::Z::L
=> NameError: uninitialized constant M::Z::L
=> M::Z.constants
=> []

module B
  class N
    X = "bar"
  end
end

=> B::N::X
=> "bar"
=> B::N.constants
=> [:X]

我看了这个,但是我不理解。


可能是Constant in class << self block的重复问题。 - toro2k
@toro2k,是的,我看到了,但这是一个不太正规的解决方法。 - Roman Kiselenko
1个回答

8

你需要按照以下步骤操作:

module M
  class Z
    class << self
      L = "foo"
    end
  end
end

M::Z.singleton_class::L # => "foo"

L是在Z的单例类中定义的。

"L"存储在M::Z的单例类常量集合中,您暂时可以称其为S。实际上,M::Z::L正在搜索L这个常量,在M::Z及其祖先的常量表中。由于它们都不是S,所以查找失败。


我忘记了关于特异类的事情)) - Roman Kiselenko
这是我的一个小恼怒。它被称为单例类 - Max

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