Search code examples
arraysrubyslicechunks

Slicing arrays based on relations in the data (in Ruby)


I have arrays in this form: [1, 2, 1, 4, 5, 4, 1, 7, 7, 6] and I need to slice them into something like [[1, 2, 1], [4, 5, 4], [1], [7, 7, 6]], where breaks are determined by the absolute difference between consecutive pairs being larger than 1.

Is there in Ruby some magic that I can harness, or am I left with having to code a plain old iteration?


Solution

  • 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]]