Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby enumerable - find up to n occurrences of matching element

Tags:

arrays

ruby

I have the following array:

arr = [1, 3, 2, 5, 2, 4, 2, 2, 4, 4, 2, 2, 4, 2, 1, 5]

I want an array containing the first three odd elements.

I know I could do this:

arr.select(&:odd?).take(3)

but I want to avoid iterating through the whole array, and instead return once I've found the third match.

I came up with the following solution, which I believe does what I want:

my_arr.each_with_object([]) do |el, memo| 
  memo << el if el.odd?; break memo if memo.size == 3 
end

But is there a more simple/idiomatic way of doing this?

like image 511
etdev Avatar asked Sep 30 '15 03:09

etdev


People also ask

What is Enumerables in Ruby?

In Ruby, we call an object enumerable when it describes a set of items and a method to loop over each of them. The built-in enumerables get their enumeration features by including the Enumerable module, which provides methods like #include? , #count , #map , #select and #uniq , amongst others.

How do you use the Find method in Ruby?

The find method locates and returns the first element in the array that matches a condition you specify. find executes the block you provide for each element in the array. If the last expression in the block evaluates to true , the find method returns the value and stops iterating.

Is Hash enumerable Ruby?

Some Ruby classes include Enumerable: Array. Dir. Hash.


1 Answers

Use a lazy enumerator with Enumerable#lazy:

arr.lazy.select(&:odd?).take(3).force
# => [1, 3, 5]

force is used to force the lazy enumerator to evaluate. Or, you could use first as it's eager:

arr.lazy.select(&:odd?).first(3)
# => [1, 3, 5]
like image 176
Yu Hao Avatar answered Sep 26 '22 20:09

Yu Hao