arrays - Ruby enumerable - find up to n occurrences of matching element -


i have following array:

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

i want array containing first 3 odd elements.

i know this:

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

but want avoid iterating through whole array, , instead return once i've found third match.

i came following solution, believe want:

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

but there more simple/idiomatic way of doing this?

use lazy enumerator enumerable#lazy:

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

force used force lazy enumerator evaluate. or, use first it's eager:

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

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -