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

时间:2009-08-09 11:12:09

标签: ruby

class A
  def a
    puts 'in #a'
  end
end

class B < A
  def a
    b()
  end
  def b
    # here i want to call A#a.
  end
end  

3 个答案:

答案 0 :(得分:80)

class B < A

  alias :super_a :a

  def a
    b()
  end
  def b
    super_a()
  end
end  

答案 1 :(得分:30)

没有很好的方法可以做到这一点,但是你可以做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

答案 2 :(得分:0)

如果你没有明确需要从B#b调用A#a,而是需要从B#a调用A#a,这实际上是你通过B#b做的事情(除非你'例子不够完整,无法证明你为什么要从B#b打电话,你可以在B#a中调用super,就像有时在初始化方法中做的一样。我知道这很明显,我只是想要澄清任何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