Is there a ruby idiom for popping items from an array while a condition is true

ruby

Solution

Maybe you are looking for `take_while`?

array = [-1, -2, 0, 34, 42, -8, -4]
result = array.reverse.take_while { |x| x < 0 }

`result` would be `[-8, -4]`.

To get the original result back you could use `drop_while` instead.

result = array.reverse.drop_while { |x| x < 0 }.reverse

`result` would be `[-1, -2, 0, 34, 42]` in this case.

Problem

Is there a Ruby idiom for popping items from an array while a condition is true, and returning the collection? I.e, ``` # Would pop all negative numbers from the end of 'array' and place them into 'result'. result = array.pop {|i| i < 0} ``` From what I can tell, something like the above doesn't exist. I'm currently using ``` result = [] while array.last < 0 do result << array.pop end ```

Original source