What’s the fastest way in Ruby to get the first enumerable element for which a block returns true?
For example:
arr = [12, 88, 107, 500]
arr.select {|num| num > 100 }.first # => 107
I’d like to do this without running through the entire array, as select will, since I only need the first match.
I know I could do an each and break on success, but I thought there was a native method for doing this; I just haven’t found it in the documentation.
Several core ruby classes, including
ArrayandHashinclude theEnumerablemodule which provides many useful methods to work with these enumerations.This module provides the
findordetectmethods which do exactly what you want to achieve:Both method names are synonyms to each other and do exactly the same.