Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 523
Nathan Long Avatar asked Mar 19 '12 12:03

Nathan Long


People also ask

What does .first do Ruby?

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.

What is enumerable in Ruby?

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.

What does .ANY return Ruby?

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.


1 Answers

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.

like image 111
Holger Just Avatar answered Sep 20 '22 19:09

Holger Just