如何从Ruby中的特定祖先类调用方法?

ala*_*dan 2 ruby oop inheritance

说,我有这样的层次结构:

class A
  def some_method
    'From A'
  end
end

class B < A
  def some_method
    'From B'
  end
end

class C < B
  def some_method
    # what's here to receive 'From A' ?
  end
end

c = C.new
c.some_method # get 'From A'
Run Code Online (Sandbox Code Playgroud)

如果我super使用C#some_method 调用,我会收到“来自B”的消息。我应该如何实现C#some_method获得'From A'c.some_method。最佳做法是什么?

iza*_*ban 5

您可以为此使用“未绑定方法”:

class A
  def some_method
    'From A'
  end
end

class B < A
  def some_method
    'From B'
  end
end

class C < B
  def some_method
    A.instance_method(:some_method).bind(self).call
  end
end

c = C.new
c.some_method # get 'From A'
Run Code Online (Sandbox Code Playgroud)

Ruby能够从对象上取消绑定方法,然后将其绑定到另一个对象。所述instance_method用于从类,而不是从这个类的特定实例抓取方法的对象。稍后,我们可以将该方法绑定到C正在调用的实例上some_method,即self,最后在同一行中立即调用该方法。

正如另一位用户所说,如果您这样做,则可能应该检查程序的设计,以使用合成或其他方法。