红宝石阵find_first反对呢? [英] Ruby Array find_first object?

查看:132
本文介绍了红宝石阵find_first反对呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我错过了Array文档中的东西吗?我有一个包含最多一个对象满足特定标准的阵列。我想有效地找到该对象。我从文档有最好的想法是这样的:

  =考生{my_array.select | E | e.satisfies_condition? }
found_it = candidates.first如果!candidates.empty?

但我不满意的原因有两个:(1)选择让我遍历整个数组,尽管我们可以在第一次袭击后已获准保释,和(2)我需要一条线code的(用条件)扁平化的人选。这两种操作都浪费与预知的有0或1的满足对象。

我想是这样的:

array.find_first(块) - >答案为零或该块计算为true,在该对象结束遍历的第一个对象。

我必须写自己?在阵列中的所有其他伟大的方式让我觉得它的存在,我只是没有看到它。

在此先感谢,


解决方案

要么我不明白你的问题,或可枚举#找是事情,你要寻找的。

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: (1) that select made me traverse the whole array, even though we could have bailed after the first hit, and (2) I needed a line of code (with a condition) to flatten the candidates. Both operations are wasteful with foreknowledge that there's 0 or 1 satisfying objects.

What I'd like is something like:

array.find_first(block) -> answers nil or the first object for which the block evaluates to true, ending the traversal at that object.

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.

Thanks in advance, Dan

解决方案

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

这篇关于红宝石阵find_first反对呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆