如何在 Ruby 中动态创建具有给定方法和方法体的类?
在 Ruby 中,如何定义一个方法
def make_class(method_name, method_body, s_value)
返回一个类并执行以下实现
class Anonymous
def method_name(args)
method_body(args)
end
def to_s
return s_value
end
end
如果您可以链接到您发现对基本 Ruby 元编程有用的任何资源也很棒。
In Ruby how would you define a method
def make_class(method_name, method_body, s_value)
returning a class with the following implementation
class Anonymous
def method_name(args)
method_body(args)
end
def to_s
return s_value
end
end
If you can link to any resources you found useful on basic Ruby metaprogramming that would be great as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以这样使用:
在这种情况下,您应该将方法的主体作为块传递(您可以将
|*args|
替换为您想要作为方法参数的任何参数列表)。如果您不想将method_body
作为块而是作为字符串传递,那么eval
就是您的朋友。You can use smth like that:
In that case you are supposed to pass your method's body as a block (you can replace
|*args|
with any list of arguments you want to have as parameters for you method). If you want to passmethod_body
not as a block but as a string theneval
is your friend.《Ruby 元编程:像 Ruby 专业人士一样编程》 是一本非常好的书了解 ruby 元编程。
"Metaprogramming Ruby: Program Like the Ruby Pros" is a very good book to learn about ruby metaprogramming.
我能想到的最简单的方法:
用法:
编辑:好的,我在这里有点太简单了,这不处理该方法的参数。
Easiest way I can think of:
Usage:
Edit: ok, I was a bit too simplistic here, this doesn't handle the args for the method.
我不建议这样做,但你可以......
返回
i would not recommend doing this, but you could...
returning