Ruby 模块类<&书信电报;自常数

Ruby 模块类<&书信电报;自常数,ruby,module,constants,self,Ruby,Module,Constants,Self,有我的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" =

有我的
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]
模块M
Z类
类M::Z::L
=>NameError:未初始化的常量M::Z::L
=>M::Z.常数
=> []
模块B
N类
X=“巴”
结束
结束
=>B::N::X
=>“巴”
=>B::N.常数
=>[:X]
我读了,但我不明白。

你需要做的是:

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

M::Z.singleton_class::L # => "foo"
模块M
Z类
“foo”类
L
Z
的单例类中定义


“L”
存储在
M::Z
的单例类的一组常量中,您现在可以称它为
S
M::Z::L
它实际上是在
M::Z
及其祖先的常量表中搜索这个常量
L
。因为没有一个是
S
,所以查找失败。

我忘记了特征类)这是我的一个恼怒。它被称为@toro2k类中常数的可能重复项是的,我看到了,但这是一个肮脏的攻击。