在ruby中调用超类的另一个方法

 A类
   def a
    放入'a'
  结束
结束

 B类<A
   def a
     B()
  结束
   def b
     #这里我想打电话给A#a。
  结束
结束  
class B < A alias :super_a :a def a b() end def b super_a() end end 

有没有好办法做到这一点,但你可以做A.instance_method(:a).bind(self).call ,这将工作,但丑陋。

你甚至可以在Object中定义你自己的方法来像java中的super一样工作:

 class SuperProxy def initialize(obj) @obj = obj end def method_missing(meth, *args, &blk) @obj.class.superclass.instance_method(meth).bind(@obj).call(*args, &blk) end end class Object private def sup SuperProxy.new(self) end end class A def a puts "In A#a" end end class B<A def a end def b sup.a end end B.new.b # Prints in A#a 

如果你不明确地需要从B#b中调用A#a,而是需要从B#a中调用A#a,这实际上是通过B#b的方式进行的(除非你是例子是不够完整的,以certificate你为什么从B#b调用,你可以从B#a中调用超级,就像有时在初始化方法中做的一样。我知道这是显而易见的,我只是想澄清对于任何你不需要别名的Ruby新手来说(特别是有时候被称为“左右别名”)。

 class A def a # do stuff for A end end class B < A def a # do some stuff specific to B super # or use super() if you don't want super to pass on any args that method a might have had # super/super() can also be called first # it should be noted that some design patterns call for avoiding this construct # as it creates a tight coupling between the classes. If you control both # classes, it's not as big a deal, but if the superclass is outside your control # it could change, w/o you knowing. This is pretty much composition vs inheritance end end