我需要一些帮助来定义一个动态方法。
基本上,我有许多类驻留在一个模块中。我需要根据传入的字符串列表在每个类中生成一个方法列表,该列表特定于每个类(即不同的类具有不同的字符串列表)。该方法的主体应该类似于:
client.call(the_string, @an_instance_variable)
所以基本上我想创建一个方法,我可以在每个驻留在同一个模块中的类中使用它,以便基于传递的字符串数组动态生成一组方法。
类似于:
register_methods @@string_array
假设"name“是数组中的一个字符串,那么它将生成如下方法:
def name
client.call("name", @an_instance_variable)
end
我希望这是有意义的。在尝试了几个小时的各种事情后,我被难住了,真的很感谢任何人的意见。谢谢!
发布于 2010-11-23 06:56:34
没有可用的irb,但这应该可以工作
def register_methods strings
strings.each do |s|
define_method s.to_sym do
client.call("name", @an_instance_variable)
end
end
end
发布于 2010-11-23 07:25:41
我不知道你打算如何使用@an_instance_variable,但你也可以像这样定义接受参数的方法:
def register_methods *methods
methods.each do |method|
define_method method do |arg|
client.call(method, arg)
end
end
end
因此,如果您发送register_methods("name","age"),您将有两个新方法,如下所示:
def name(arg)
client.call("name", arg)
end
def age(arg)
client.call("age", arg)
end
https://stackoverflow.com/questions/4253327
复制