2010-10-20 74 views
1

假設我有兩個類,像這樣:調用超類的方法與扭曲

class Parent 
    def say 
    "I am a parent" 
    end 
end 

class Child < Parent 
    def say 
    "I am a child" 
    end 

    def super_say 
    #I want to call Parent.new#say method here 
    end 
end 

什麼是做到這一點的選擇?我認爲:

def super_say 
    self.superclass.new.say #obviously the most straight forward way, but inefficient 
end 

def super_say 
m = self.superclass.instance_method(:say) 
m = m.bind(self) 
m.call 
#this works, but it's quite verbose, is it even idiomatic? 
end 

我找不涉及混淆Parent.new#的方式說別的東西,這將使它的方法查找鏈中唯一的(或者是實際的首選方式?)。 有什麼建議嗎?

回答

2

我傾向於使用別名。 (我不是很確定我理解你反對它。)

例子:

class Child < Parent 
    alias :super_say :say 

    def say 
    "I am a child" 
    end 
end 

給出:

irb(main):020:0> c = Child.new 
=> #<Child:0x45be40c> 
irb(main):021:0> c.super_say 
=> "I am a parent" 
0

你的第二個解決方案(bind())是我會去的。這是冗長的,因爲你所做的事情非常不尋常,但如果你真的需要這樣做的話 - 那個解決方案對我來說似乎很好。