2010-10-20 77 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())是我会去的。这是冗长的,因为你所做的事情非常不寻常,但如果你真的需要这样做的话 - 那个解决方案对我来说似乎很好。