Search code examples
arraysruby

How to fetch the first matching item from an array


Given an array: [1, 2, 3, 5, 8. 13]

I can select all items greater than 3:

[1, 2, 3, 5, 8. 13].select { |num| num > 3 }

(I am aware of the shorthand select(&:>) syntax, that is not the point here)

I can now return the first, easily.

[1, 2, 3, 5, 8. 13].select { |num| num > 3 }.first

But when the actual comparison is getting heavy, this is not very efficient. I am trying to optimize a case where we have arrays of 300+ items, the select will return one of the first in nearly all cases (and the array is already sorted). Moreover, our code to do the comparison is quite heavy (needs a roundtrip to the db, for example).

Is there a ruby shorthand to fetch the first and then stop? Similar to:

[1, 2, 3, 5, 8. 13].each do |num|
   return num if num > 3
end

Solution

  • You can use Enumerable#find:

    [1, 2, 3, 5, 8, 13].find { |num| num > 3 }
    #=> 5