Ruby Array find_first 对象?

人气:938 发布:2022-10-16 标签: performance ruby arrays find

问题描述

我是否遗漏了 Array 文档中的某些内容?我有一个数组,其中最多包含一个满足某个标准的对象.我想有效地找到那个对象.我从文档中得到的最好的想法是:

Am I missing something in the Array documentation? I have an array which contains up to one object satisfying a certain criterion. I'd like to efficiently find that object. The best idea I have from the docs is this:

candidates = my_array.select { |e| e.satisfies_condition? }
found_it = candidates.first if !candidates.empty?

但我不满意有两个原因:

But I am unsatisfied for two reasons:

那个 select 让我遍历了整个数组,尽管我们本可以在第一次命中后放弃.我需要一行代码(带有条件)来扁平化候选人. That select made me traverse the whole array, even though we could have bailed after the first hit. I needed a line of code (with a condition) to flatten the candidates.

这两种操作都是浪费的,因为预先知道有 0 或 1 个令人满意的对象.

Both operations are wasteful with foreknowledge that there's 0 or 1 satisfying objects.

我想要的是这样的:

array.find_first(block)

它返回 nil 或该块计算为真的第一个对象,结束对该对象的遍历.

which returns nil or the first object for which the block evaluates to true, ending the traversal at that object.

我必须自己写吗?Array 中所有其他很棒的方法让我觉得它就在那里,我只是没有看到它.

Must I write this myself? All those other great methods in Array make me think it's there and I'm just not seeing it.

推荐答案

要么我不明白你的问题,要么 Enumerable#find 就是你要找的东西.

Either I don't understand your question, or Enumerable#find is the thing you were looking for.

134