2013-05-04 86 views
3

我有幾類,如P,共享相同的實例方法some_method自動調用每當一個實例被調用的方法

class P 
    ... 
    def some_method 
    @id 
    end 
end 

這些類的實例會在許多地方,像這樣用作參數:

p = P.new 
q = Q.new 
... 

def some_outside_method(p,q,r,s) 
    another_outside_method(p.some_method, q.some_method, r.some_method, s.some_method) 
end 

我想知道是否有更優雅的寫作方式。每當p被引用時,是否可以自動調用psome_methodsome_outside_method(p)?它類似to_s隱含地由puts調用,但是更一般化。

+1

定義'P#id'時定義'P#some_method'有什麼意義? – sawa 2013-05-04 18:44:32

+0

這個問題也不太清楚? OP究竟想要做什麼? – 2013-05-04 18:45:18

+1

@sawa,你是對的。對不起,我只是想簡化案件;實際的事情更復雜。這只是我當時想到的一個例子。並且非常感謝您幫助我編輯問題! – zuhao 2013-05-04 19:14:00

回答

3

你可以這樣做減少重複,例如:

def some_outside_method(p,q,r,s) 
    args = [p, q, r, s].map{|o| o.send(:some_method)} 
    another_outside_method(*args) 
end 

,或者更簡單:

def some_outside_method(*args) 
    args = args.map(&:some_method) 
    another_outside_method(*args) 
end 

,或者更更簡單:

def some_outside_method(*args) 
    another_outside_method args.map(&:some_method) 
end 

不過不要」噸。簡單的代碼比簡潔和「聰明」的更好。

+0

哪裏定義了'some_outside_method'方法?誰會從哪裏調用它? – 2013-05-04 18:43:41

+0

非常感謝!這好多了。 – zuhao 2013-05-04 19:20:36

相關問題