将动态定义的类作为常量访问仅适用于const_get

时间:2017-01-13 03:50:00

标签: ruby

给出以下示例:

[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)>
  1. 为什么当我Foo.constants它返回一个常量时。它不应该返回[:Foo, :BarLol]

  2. 另外,为什么能够访问动态定义常量值的唯一方法是Foo.const_get('BarLol')?为什么Foo::BarLol不起作用?

1 个答案:

答案 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