I have the following array:
arr = [1, 3, 2, 5, 2, 4, 2, 2, 4, 4, 2, 2, 4, 2, 1, 5]
I need an array containing the first three odd elements.
I know I can do this:
arr.select(&:odd?).take(3)
but I want to avoid iterating over the entire array, and will come back instead as soon as I find 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 an easier / idiomatic way to do this?
etdev source share