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.
The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.
Enumeration refers to traversing over objects. In Ruby, we call an object enumerable when it describes a set of items and a method to loop over each of them.
The any?() of enumerable is an inbuilt method in Ruby returns a boolean value if any of the object in the enumerable satisfies the given condition, else it returns false.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With