gpt4 book ai didi

ruby - 覆盖#each;我可以通过#map、#select 等传递参数吗?

转载 作者:太空宇宙 更新时间:2023-11-03 16:26:55 25 4
gpt4 key购买 nike

我已经编写了自己的 Tree 类,其中包括 EnumerableTree 然后提供了一个 #each 函数。因此,它能够自动获取所有 Enumerable 函数,如 #map#select#find,等等。到目前为止,这一切都适用于我的代码。

问题来了。当我为我的 Tree 编写 #each 时,我给了 #each 一个参数,它是要使用的树遍历算法的名称,例如:pre_order:breadth_first。但是现在当我调用#map#inject#any? 等等时,它只能使用默认的遍历算法。有什么办法可以通过其他 Enumerable 函数传递这个参数吗?这是我的标准;

  • 我需要能够对任何 Enumerable 函数使用任何遍历算法。这一点非常重要,因为树对于不同的算法可能具有非常不同的性能。
  • 我不想重写每个 Enumerable 函数来将这个参数传递给 #each;这违背了模块的目的。

这是我的代码的简化版本;

class Tree
include Enumerable
...

# Overwrite #each, and give it the algorithm argument.
def each(algorithm = :pre_order, &block)
if TRAVERSAL_ALGORITHMS.include? algorithm
self.send(algorithm, &block)
else
self.method_missing(algorithm)
end
end

def pre_order(&block)
yield self
self.branches.each do |branch|
branch.pre_order(&block)
end
end

def post_order(&block)
...
end

def breadth_first(&block)
...
end

end

我想这样调用;

tree.find(13, :breadth_first)
tree.any?(:post_order) do |node|
node.root >= 10
end

最佳答案

我好傻。

#enum_for 方法赋予了我所有的力量。我可以实现 Charlie 的语法

tree.breadth_first.find(13)

通过添加常规行

return self.enum_for(__method__) unless block_given?

在我的每一个遍历方法中。 tree.breadth_first 会返回一个Enumerator,按照广度优先算法进行枚举;调用的任何 Enumerable 方法都将在内部使用该枚举。

关于ruby - 覆盖#each;我可以通过#map、#select 等传递参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23197442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com