Search code examples
rubyarraysenumerable

What's the fastest way in Ruby to get the first enumerable element for which a block returns true?


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.


Solution

  • 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.