Ruby array access 2 consecutive(chained) elements at a time

arrays, each, ruby

Solution

Ruby reads your mind. You want cons ecutive elements?

[1, 2, 3, 4, 5, 6, 7, 8, 9].each_cons(2).to_a
# => [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]

Problem

Now, This is the array, ``` [1,2,3,4,5,6,7,8,9] ``` I want, ``` [1,2],[2,3],[3,4] upto [8,9] ``` When I do, each_slice(2) I get, ``` [[1,2],[3,4]..[8,9]] ``` Im currently doing this, ``` arr.each_with_index do |i,j| p [i,arr[j+1]].compact #During your arr.size is a odd number, remove nil. end ``` Is there a better way??

Original source

Related problems