繁体   English   中英

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

[英]calling another method in super class in 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
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做的事情(除非你是一个例子)还不够完整,无法证明你为什么要从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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM