2010-11-23 62 views
1

我需要一些帮助来定义动态方法。Ruby动态方法帮助

基本上,我有很多类在一个模块内。我需要根据传入的字符串列表来生成每个类中的方法列表,这些列表对每个类都是特定的(即不同的类具有不同的字符串列表)。该方法的主体应该是这样的:

client.call(the_string, @an_instance_variable) 

所以基本上我要创建我可以在这些类所在的同一模块内的使用方法,以便动态生成一串方法基于传递的字符串数组。

喜欢的东西:

register_methods @@string_array 

所以说,“名”是在数组中的字符串,那么这将产生一个方法,例如:

def name 
    client.call("name", @an_instance_variable) 
end 

我希望是有道理的。几个小时后我尝试了各种各样的东西,我很难过,并且会很感激任何输入。谢谢!

回答

4

没有一个IRB可用,但这应该工作

def register_methods strings 
    strings.each do |s| 
    define_method s.to_sym do 
     client.call("name", @an_instance_variable) 
    end 
    end 
end 
0

我不知道你打算怎么办使用@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( “姓名”, “年龄”),你将有两个新的方法看起来像这样:

def name(arg) 
    client.call("name", arg) 
end 

def age(arg) 
    client.call("age", arg) 
end