我正在使用一个像这样放置库的库:
module Lib
class A; end
class B; end
...
end
我知道我可以在对象上使用send
来“调用”仅在运行时知道的方法(例如,foo.send(:bar, :baz_param=>42
)。我怎样才能在班级做到这一点?
换句话说,我怀疑有办法写这样的东西:
label = :Klass
MyModule.some_method(label).new
实际上执行为:
MyModule::Klass.new
我是对的吗?
答案 0 :(得分:2)
我一发布这个问题,就有了脑波:
const_get
类名被视为常量,并且该方法也是为所有模块定义的,因此查找范围只能限制在该模块中。只记得正确的大写:
MyModule.const_get(:Klass).new # => #<Klass:> #CORRECT
MyModule.const_get(:klass).new # => NameError: wrong constant name