ruby - 如何在 Ruby 中调用特定祖先类的方法?

标签 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'

如果我在 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_methodC 实例,即 self,最终在同一条线。

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

关于ruby - 如何在 Ruby 中调用特定祖先类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39985925/

相关文章:

c# - 自动映射器以及从集合或列表继承

ruby - 尝试使用 Selenium Webdriver v3.70 最大化浏览器窗口时出现 Ruby "KeyError: key not found: 102"错误

ruby-on-rails - 如何从 ActiveRecord 中名为 "object_id"的列中检索值?

ruby - 如何使用 Ruby 在 Appium 中验证键盘是否打开

Java - 对象多次创建自身 - 有任何设计模式吗?

oop - 默认情况下,私有(private)属性是否被 .perl 和 .gist 隐藏

c# - 通过继承使用 IDisposable

ruby-on-rails - 安装 Ruby Gems 时遇到问题?

php - 面向对象设计 : Return Values or Set Property?

java - 泛型将子类添加到数组