2010-11-23 63 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