给出以下示例:
[1] pry(main)>
[2] pry(main)> module Foo
[2] pry(main)* Foo = 'LOL'
[2] pry(main)* ['Lol'].each do |elem|
[2] pry(main)* @elem = elem
[2] pry(main)* Object.const_set "Bar#{elem}", Class.new { def butts; puts "#{@elem}" end; }
[2] pry(main)* end
[2] pry(main)* end
=> ["Lol"]
[3] pry(main)> Foo.constants
=> [:Foo]
[4] pry(main)> Foo.const_get('BarLol')
=> BarLol
[5] pry(main)> Foo::Foo
=> "LOL"
[6] pry(main)> Foo::BarLol
NameError: uninitialized constant Foo::BarLol
from (pry):11:in `<main>'
[7] pry(main)>
为什么当我Foo.constants
它返回一个常量时。它不应该返回[:Foo, :BarLol]
?
另外,为什么能够访问动态定义常量值的唯一方法是Foo.const_get('BarLol')
?为什么Foo::BarLol
不起作用?
答案 0 :(得分:4)
问题是,您在BarLol
的范围内设置Object
不变,而不是Foo
的范围,只需稍作更改即可:
module Foo
Foo = 'LOL'
['Lol'].each do |elem|
@elem = elem
::Foo.const_set "Bar#{elem}", Class.new { def butts; puts "#{@elem}" end; }
end
end
p Foo.constants
#=> [:Foo, :BarLol]
p Foo.const_get('BarLol')
#=> Foo::BarLol
p Foo::Foo
#=> "LOL"
p Foo::BarLol
#=> Foo::BarLol