First element of an array with condition

RubyArrays

Ruby Problem Overview


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} ]

Ruby Solutions


Solution 1 - Ruby

Try this:

my_array.find{|x| x.some_test }

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

my_array.find(&:some_test)

Solution 2 - Ruby

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

I prefer to use detect for getting distinct one.

And select for finding all of them.

Here what ruby docs tells about them:

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.

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBalzardView Question on Stackoverflow
Solution 1 - RubySergio TulentsevView Answer on Stackoverflow
Solution 2 - RubysarvavijJanaView Answer on Stackoverflow