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
Post a Comment