Quantcast
Channel: Active questions tagged ruby - Stack Overflow
Viewing all articles
Browse latest Browse all 4628

How to fetch the first matching item from an array

$
0
0

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 > 3end

Viewing all articles
Browse latest Browse all 4628

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>