我如何调用超类方法

我有两个AB类。 B类重写A类的foo方法。 B类有一个bar方法,我想调用超类的foo方法。 这种电话的语法是什么?

 class A def foo "hello" end end class B < A def foo super + " world" end def bar # how to call the `foo` method of the super class? # something similar to super.foo end end 

对于类方法,我可以通过显式地为类名添加前缀来调用inheritance链中的方法。 我想知道是否有类似的习惯用法。

 class P def self.x "x" end end class Q < P def self.x super + " x" end def self.y Px end end 

编辑我的用例是一般的。 对于特定情况,我知道我可以使用alias技术。 这是Java或C ++中的常见function,所以我很想知道是否可以在不添加额外代码的情况下执行此操作。

在Ruby 2.2中,您现在可以使用Method#super_method

例如:

 class B < A def foo super + " world" end def bar method(:foo).super_method.call end end 

参考: https : //bugs.ruby-lang.org/issues/9781#change-48164和https://www.ruby-forum.com/topic/5356938

你可以做:

  def bar self.class.superclass.instance_method(:foo).bind(self).call end 

在这种特殊情况下,您可以使用alias :bar :fooclass B def foo alias :bar :foo之前将旧的foo重命名为bar ,但当然您可以使用任何名称的别名并从中调用它。 这个问题有一些替代方法可以在inheritance树中进一步完成。

您可以在重新定义alias old_foo foo之前使用alias old_foo foo ,以便在旧名称下保留旧实现。 (从技术上讲,可以采用超类的实现并将其绑定到子类的实例,但它很hacky,并非完全没有惯用,并且在大多数实现中可能都很慢。)

基于@Sony的回答。

如果你想在某些my_object上调用method方法并且它已经覆盖了几个更高的类(比如Net::HTTPRequest#method ),而不是做.superclass.superclass.superclass使用:

 Object.instance_method(:method).bind(my_object) 

像这样:

 p Object.instance_method(:method).bind(request).call(:basic_auth).source_location