Search code examples
rubyenumerable

how to enumerate continuous elements in an array?


For instance, I have a

arr = [1,2,3,4]

If I call arr.each, I will access:

1
2
3
4

But I want

1 2
2 3
3 4

Is it possible with built-in function? If not, what's the best practice?

Another question: if I want 1 2 and 3 4?


Solution

  • You probably want to look at each_cons for your first case:

    (1..10).each_cons(3) {|a| p a}
    # outputs below
    [1, 2, 3]
    [2, 3, 4]
    [3, 4, 5]
    [4, 5, 6]
    [5, 6, 7]
    [6, 7, 8]
    [7, 8, 9]
    [8, 9, 10]
    

    For your second case (wanting sets of elements) you would use each_slice:

    (1..10).each_slice(3) {|a| p a}
    # outputs below
    [1, 2, 3]
    [4, 5, 6]
    [7, 8, 9]
    [10]
    

    Either of these methods accepts a single integer specifying the size of the set, so you would specify 2 instead of 3 (examples are straight from the documentation).