First element of an array with condition
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} ]
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)
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