What's the fastest way in Ruby to get the first enumerable element for which a block returns true?
Several core ruby classes, including Array
and Hash
include the Enumerable
module which provides many useful methods to work with these enumerations.
This module provides the find
or detect
methods which do exactly what you want to achieve:
arr = [12, 88, 107, 500]arr.find { |num| num > 100 } # => 107
Both method names are synonyms to each other and do exactly the same.
I remember this using by thinking of ActiveRecord.find, which gets you the first record and ActiveRecord.select, which you use when you're getting all of them.
Not a perfect comparison but might be enough to help remember.