比如说,我有这样的层次结构:
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'
如果我在 C#some_method 中调用 super
,我将收到“From B”。
我应该如何实现 C#some_method 以在 c.some_method
中获取 'From A'
。
执行此操作的最佳做法是什么?
最佳答案
您可以为此使用“未绑定(bind)方法”:
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'
Ruby 能够将方法与对象解除绑定(bind),然后将其绑定(bind)到另一个对象。 instance_method
用于从类而不是此类的特定实例中获取方法对象。稍后,我们可以将该方法绑定(bind)到调用 some_method
的 C
实例,即 self
,最终在同一条线。
正如另一位用户所说,如果您正在这样做,您可能应该检查程序的设计以使用组合或其他方法。
关于ruby - 如何在 Ruby 中调用特定祖先类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39985925/