ruby 带条件的数组的第一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13339778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:31:04  来源:igfitidea点击:

First element of an array with condition

rubyarrays

提问by Balzard

Is there a shorter way to find the first element in an array meeting some conditions than this:

有没有比这更短的方法来找到满足某些条件的数组中的第一个元素:

my_array[ my_array.index {|x| x.some_test} ]

回答by Sergio Tulentsev

Try this:

尝试这个:

my_array.find{|x| x.some_test }

Or here's a shortcut (thanks @LarsHaugseth for reminding about it)

或者这是一个快捷方式(感谢@LarsHaugseth 提醒)

my_array.find(&:some_test)

回答by sarvavijJana

As for me find sounds confusing. As i am expecting receive more than one object for such a request.

至于我觉得听起来很混乱。因为我期待收到不止一个这样的请求对象。

I prefer to use detectfor getting distinct one.

我更喜欢使用detect来获得独特的。

And selectfor finding all of them.

select找到所有这些。

Here what ruby docs tells about them:

以下是 ruby​​ 文档对它们的描述:

detect(ifnone = nil) {| obj | block } → obj or nil click to toggle source 
find(ifnone = nil) {| obj | block } → obj or nil 
detect(ifnone = nil) → an_enumerator 
find(ifnone = nil) → an_enumerator

Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns nil otherwise.

将枚举中的每个条目传递到块。返回块不为假的第一个。如果没有对象匹配,则调用 ifnone 并在指定时返回其结果,否则返回 nil。

find_all {| obj | block } → array click to toggle source
select {| obj | block } → array
find_all → an_enumerator
select → an_enumerator

Returns an array containing all elements of enum for which block is not false

返回一个数组,其中包含不为 false 的 enum 的所有元素