I want to get all items from an array, which satisfy a predicate. Once I see an element that doesn't satisfy, I should stop iterating. For example:
[1, 4, -9, 3, 6].select_only_first { |x| x > 0}
I'm expecting to get: [1, 4]
This is how you want :
arup@linux-wzza:~> pry
[1] pry(main)> [1, 4, -9, 3, 6].take_while { |x| x > 0}
=> [1, 4]
[2] pry(main)>
Here is the documentation :
arup@linux-wzza:~> ri Array#take_while
= Array#take_while
(from ruby site)
------------------------------------------------------------------------------
ary.take_while { |arr| block } -> new_ary
ary.take_while -> Enumerator
------------------------------------------------------------------------------
Passes elements to the block until the block returns nil or false, then stops
iterating and returns an array of all prior elements.
If no block is given, an Enumerator is returned instead.
See also Array#drop_while
a = [1, 2, 3, 4, 5, 0]
a.take_while { |i| i < 3 } #=> [1, 2]
lines 1-20/20 (END)
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