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.
arr.find{|el| el>100} #107 (or detect; it's in the Enumerable module.)