有我的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]
我读了this但我不明白。
最佳答案
你需要这样做:
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
它实际上是在 M::Z
及其祖先的常量表中搜索这个常量 L
。因为它们都不是 S
,所以查找失败。
关于ruby - 模块类 << 自常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22345835/