如何调用grand-parent的方法,并在ruby中跳过父级

Dan*_*iel 2 ruby inheritance super

如何在继承链中选择特定的方法调用?

class A
  def boo; puts "A:Boo"; end
end

class B < A
  def boo; super; puts "B:Boo"; end
end

class C < B
  def boo; self.A.boo(???); puts "C:Boo"; end
end
Run Code Online (Sandbox Code Playgroud)

因此输出将是A:Boo,C:Boo

TIA,

-daniel

sep*_*p2k 5

你可以做

class C < B
  def boo
    A.instance_method(:boo).bind(self).call
    puts "C:Boo"
  end
end
Run Code Online (Sandbox Code Playgroud)

但是,如果您需要这个,那通常表明您应该重新考虑您的设计.特别是如果C需要A的实现boo,B可能不应该覆盖它.

  • 我会反过来说:如果C不应该像B一样,那么C不应该是B的子类. (2认同)