在 Ruby 中,我如何反映模块中包含的类?
我使用的库的布局如下:
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
Am我说得对吗?
I'm using a library that lays its library out like this:
module Lib
class A; end
class B; end
...
end
I know that I can use send
on an object to "call" a method known only at runtime (e.g., foo.send(:bar, :baz_param=>42
). How can I do this at the class level?
In other words, I suspect there's a way to write something like this:
label = :Klass
MyModule.some_method(label).new
that executes, in effect, as:
MyModule::Klass.new
Am I right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题一发出来,我灵机一动:
const_get
类名被视为常量,方法也是为所有模块定义的,所以查找范围只能限制在该模块内。只要记住大小写正确即可:
As soon as I posted the question, I had a brainwave:
const_get
Class names are treated as constants, and the method is defined for all modules, too, so the lookup scope can be restricted to that module only. Just remember to get the capitalization right: