2013-02-11 158 views
0

調用類方法的替代方式,我想傳遞一個類方法作爲參數有另一個對象調用它即通過PARAM或字符串

do_this(Class.method_name) 

然後:

def do_this(class_method) 
    y = class_method(local_var_x) 
end 

唯一我可以看到的做法是將它作爲字符串傳遞並使用eval,或者將該類和方法作爲字符串傳遞,然後進行常量化和發送。 eval的下滑似乎是速度和調試?

有沒有更簡單的方法來做到這一點?

編輯:

很好的答案,但意識到我問的問題稍有不妥,想用不與方法傳遞的參數。

回答

3

我會建議一種類似於您提出的第二種解決方案的方法。

do_this(Class.method(:name), x) 

然後:

def do_this(method, x) 
    y = method.call(x) 
end 

也見Object#method的文檔。

1

考慮使用一個進程內對象:

def do_this(myproc) 
    y = myproc.call 
end 

然後

do_this(Proc.new { klass.method(x) }) 

但你也應該考慮使用塊,這是在紅寶石的風格等等。這將是這樣的:

def do_this 
    y = yield 
end 

,並通過撥打:

do_this { klass.method(x) } 
+0

+1塊形式。 – 2013-02-12 00:28:29