Roman Kiselenko
Roman Kiselenko

Reputation: 44370

Module class << self constants

Is there my L constants?

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]

I read this but I do not understand.

Upvotes: 4

Views: 1241

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118271

You need to do as :

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

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

L is defined inside the singleton class of Z.

"L" is stored in the set of constants of the singleton class of M::Z, You may call it S for now. M::Z::L it actually is searching this constant L, in the constant table of M::Z and its ancestors. since none of them is S, the look-up fails.

Upvotes: 8

Related Questions