如何在不使用 eval 的情况下动态调用类?
是否可以去掉下面的eval语句? 下面的代码过滤掉从 BaseClass 类型派生的所有类。 之后这些类被实例化并调用方法“hello”。
module MySpace
class BaseClass
def hello; print "\nhello world"; end
end
class A<BaseClass
def hello; super; print ", class A was here"; end
end
class B<BaseClass
def hello; super; print ", I'm just a noisy class"; end
end
MySpace.constants.each do | e |
c=eval(e)
if c < BaseClass
c.new.hello
end
end
end
所以执行后输出是:
hello world, I'm just a busy class
你好,世界,A 类在这里
我认为不必要的使用 eval 是邪恶的。 我不确定这里是否强制使用 eval 。 是否有一种更智能的方法来动态调用“BaseClass”类型中的所有类?
Is it possible to get rid of the eval statement below? The code below filters out all classes which are derived from type BaseClass. Afterwards those classes are instantiated and method 'hello' is called.
module MySpace
class BaseClass
def hello; print "\nhello world"; end
end
class A<BaseClass
def hello; super; print ", class A was here"; end
end
class B<BaseClass
def hello; super; print ", I'm just a noisy class"; end
end
MySpace.constants.each do | e |
c=eval(e)
if c < BaseClass
c.new.hello
end
end
end
So after execution the output is:
hello world, I'm just a noisy class
hello world, class A was here
I think unnecessary use of eval is evil. And I'm not sure if the use of eval is mandatory here. Is there is a smarter way in invoking all classes from type "BaseClass" dynamically?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
eval 是我所知道的将字符串转换为常量的唯一方法。 甚至 Rails 也是这样做的:
http://api.rubyonrails.com/classes/Inflector.html#M001638
奇怪的是常量返回字符串。
eval is the only way I know of to turn a string into a constant. Its even the way rails does it:
http://api.rubyonrails.com/classes/Inflector.html#M001638
The odd thing is that constants returns strings.
您是否看过
class_eval
?Have you looked at
class_eval
instead?