【问题标题】:Use mixin method over inherited one使用 mixin 方法而不是继承的方法
【发布时间】:2017-03-09 22:38:05
【问题描述】:

假设我创建了以下类:

class Node < Struct.new(:data, :left, :right)
  def each(&block)
    ...
  end
end

如您所知,selectStructEnumerable 定义(后者包含在Struct 中)。

我该如何做Node.new.select 并触发Enumerable 的实现而不是Struct 的实现?我需要这个的原因是我已经为我的班级实现了一个自定义each,我希望select 使用它(因此我需要Enumerable#select)。

【问题讨论】:

    标签: ruby inheritance mixins


    【解决方案1】:

    如果你可以修改Node的源代码,那就让它prepend Enumerable而不是include Enumerable

    如果你不能,那么你可以从Enumerablebind它的实例方法select获取Node的实例,然后call它。

    node = Node.new(...)
    Enumerable.instance_method(:select).bind(node).call
    

    【讨论】:

      【解决方案2】:

      像这样:

      class Node < Struct.new(:data, :left, :right)
        #... 
        define_method(:select, Enumerable.instance_method(:select)) 
      end
      

      无耻插件:这是RubyTapas #466, "Ancestral Behavior"的话题

      【讨论】:

      • 看起来不错,但我更喜欢@Aetherus 的解决方案。尽管它可能隐藏了除select 之外的Struct 的其他常用方法。
      • @aetherus 解决方案不会隐藏任何东西。
      • 嗯,第二个解决方案没有。我明白你对第一个解决方案的意思。
      猜你喜欢
      • 2016-06-04
      • 2017-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-09
      • 2022-01-11
      • 1970-01-01
      相关资源
      最近更新 更多