模块类 << 自常量

Зел*_*ный 3 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"
=> B::N.constants
=> [:X]
Run Code Online (Sandbox Code Playgroud)

我读了这个,但我不明白。

Aru*_*hit 5

你需要这样做:

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

M::Z.singleton_class::L # => "foo"
Run Code Online (Sandbox Code Playgroud)

L在 的单例类中定义Z

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