2011-11-07 61 views
33

我有兩個方法在我的ruby文件中定義。Ruby將字符串轉換爲方法名稱

def is_mandatory(string) 
     puts xyz 
end 
def is_alphabets(string) 
     puts abc 
end 

包含的方法的名稱的數組。

methods = ["is_mandatory", "is_alphabets"] 

當我做了以下

methods.each do |method| puts method.concat("(\"abc\")") end 

它只是顯示,is_mandatory( 「ABC」)is_alphabets( 「ABC」),而不是實際調用該方法。

如何將字符串轉換爲方法名稱? 任何幫助,不勝感激。

乾杯!

+3

在附註上,Ruby做的is_ *方法是使用問號而不是前綴「is」,即'mandatory?'和'alphabets?'。 –

回答

50

最好的辦法可能是:

methods.each { |meth| send(meth, 'abc') } 

Object#send

+0

謝謝你的工作! – verdure

+0

如果這些方法屬於某個類? –

+2

然後你想要的東西是:'obj = OwningClass.new; methods.each {| meth | obj.send(meth,'abc')}' – Chowlett

12

嘗試使用 「發送」。

methods.each do |method| 
    self.send(method, "abc") 
end