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?
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.
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.
Some Ruby classes include Enumerable: Array. Dir. Hash.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With