Reputation: 126012
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.
Upvotes: 46
Views: 18391
Reputation: 346
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.
Upvotes: 0
Reputation: 55823
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.
Upvotes: 83
Reputation: 80075
arr.find{|el| el>100} #107 (or detect; it's in the Enumerable module.)
Upvotes: 3