Let's say I have an array of numbers, e.g.
ary = [1, 3, 6, 7, 10, 9, 11, 13, 7, 24]
I would like to split the array between the first point where a smaller number follows a larger one. My output should be:
[[1, 3, 6, 7, 10], [9, 11, 13, 7, 24]]
I've tried slice_when
and it comes quite close:
ary.slice_when { |i, j| i > j }.to_a
#=> [[1, 3, 6, 7, 10], [9, 11, 13], [7, 24]]
But it also splits between 13
and 7
, so I have to join the remaining arrays:
first, *rest = ary.slice_when { |i, j| i > j }.to_a
[first, rest.flatten(1)]
#=> [[1, 3, 6, 7, 10], [9, 11, 13, 7, 24]]
which looks a bit cumbersome. It also seems inefficient to keep comparing items when the match was already found.
I am looking for a general solution based on an arbitrary condition. Having numeric elements and i > j
is just an example.
Is there a better way to approach this?