gpt4 book ai didi

Ruby Enumerable#find 返回映射值

转载 作者:数据小太阳 更新时间:2023-10-29 08:43:00 26 4
gpt4 key购买 nike

Ruby 的 Enumerable 是否提供更好的方法来执行以下操作?

output = things
.find { |thing| thing.expensive_transform.meets_condition? }
.expensive_transform

Enumerable#find非常适合在可枚举中查找元素,但会返回原始元素,而不是 block 的返回值,因此所有完成的工作都会丢失。

当然有一些丑陋的方法可以做到这一点......

副作用

def constly_find(things)
output = nil

things.each do |thing|
expensive_thing = thing.expensive_transform
if expensive_thing.meets_condition?
output = expensive_thing
break
end
end

output
end

从 block 中返回

这是我要重构的备选方案

def costly_find(things)
things.each do |thing|
expensive_thing = thing.expensive_transform

return expensive_thing if expensive_thing.meets_condition?
end

nil
end

each.lazy.map.find

def costly_find(things)
things
.each
.lazy
.map(&:expensive_transform)
.find(&:meets_condition?)
end

还有更好的吗?

最佳答案

Of course there are ugly ways of accomplishing this...

如果您的操作成本低,您只需使用:

collection.map(&:operation).find(&:condition?)

要使 Ruby 仅“按需”调用 operation(如文档所述),您可以简单地在前面添加 lazy :

collection.lazy.map(&:operation).find(&:condition?)

我认为这一点都不丑——恰恰相反——我觉得它很优雅。


应用于您的代码:

def costly_find(things)
things.lazy.map(&:expensive_transform).find(&:meets_condition?)
end

关于Ruby Enumerable#find 返回映射值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46902273/

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