【问题标题】:How to call a method from a specific ancestor class in Ruby?如何从 Ruby 中的特定祖先类调用方法?
【发布时间】:2017-02-20 12:10:25
【问题描述】:

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

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,我将收到“来自 B”。 我应该如何实现 C#some_method 在c.some_method 中获取'From A'。 这样做的最佳做法是什么?

【问题讨论】:

  • 这可以通过拥有一个从B 分支的B2 类来解决,而无需重新定义该方法。
  • 所以你是说有时Cs 是Bs 有时不是?我倾向于在这里同意@bjhaid,C &lt; B 听起来不是正确的方法(但我可能是错的)。
  • 嗯,Cs 是 Bs,但它们也是 As。所以这里的作曲听起来不错。
  • 我的评论去哪儿了? :o

标签: ruby oop inheritance


【解决方案1】:

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

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 能够将方法与对象解除绑定,然后将其绑定到另一个对象。 instance_method 用于从类中获取方法对象,而不是从此类的特定实例中获取。稍后,我们可以将该方法绑定到调用some_methodC 的实例,就是self,最后在同一行中立即调用该方法。

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

【讨论】:

  • 你比我快 1 秒 :D
猜你喜欢
  • 1970-01-01
  • 2010-10-14
  • 1970-01-01
  • 2011-04-11
  • 2010-12-31
  • 2013-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多