Slicing arrays based on relations in the data (in Ruby) -
i have arrays in form: [1, 2, 1, 4, 5, 4, 1, 7, 7, 6]
, need slice them [[1, 2, 1], [4, 5, 4], [1], [7, 7, 6]]
, breaks determined absolute difference between consecutive pairs being larger 1.
is there in ruby magic can harness, or left having code plain old iteration?
you can use enumerable#slice_when
:
a = [1, 2, 1, 4, 5, 4, 1, 7, 7, 6] a.slice_when { |i, j| (i - j).abs > 1 }.to_a #=> [[1, 2, 1], [4, 5, 4], [1], [7, 7, 6]]
Comments
Post a Comment