2013-05-04 73 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

相关问题