2012-02-27 60 views
1

我必須動態調用對象obj上的方法列表。 我想實例化一個方法對象,然後調用它。紅寶石字符串方法名稱錯誤:未定義的方法調用='爲#<方法:0xa396aac>(NoMethodError)

method_name(字符串)是可以在對象obj上調用的方法的名稱。

meth=obj.method(method_name) #method_name is a string 
meth.call = mod 

我收到以下錯誤:

未定義的方法`#爲調用=」(NoMethodError)

我使用ORM的續集,並有動態保存模型關聯。 如果我直接調用METHOD_NAME(當method_name是不是一個字符串)正在

obj.method_name = mod #working 

然而,當method_name是一個字符串下面,是給一個語法錯誤如下:

obj.send(method_name) = mod #not working 

語法錯誤,意外'=',期待keyword_end

所以我無法使用上述任何方式從字符串形式的名稱中調用方法。

+0

可能與http://stackoverflow.com/questions/621176/how-to-dynamically-call-accessor-methods-in-ruby重複 – Baldrick 2012-02-27 08:49:50

回答

3

如果命名method_name的方法將mod參數嘗試:

obj.send(method_name, mod) 

如果您分配的東西,那麼method_name應該=結束。

0

call正確的語法是

call(args, ...) 

[ref]

(不要把=電話後,只列出以逗號分隔arguemnts)

而且Ingenu's方法,是也是做類似事情的一個好方法(可能更好)。

相關問題