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]]
.each_cons does exactly what you want.
.each_cons
[1] pry(main)> a = [1,2,3,4,5,6,7,8,9]=> [1, 2, 3, 4, 5, 6, 7, 8, 9][2] pry(main)> a.each_cons(2).to_a=> [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]
You almost got it right :)
arr = [1,2,3,4,5,6,7,8,9]arr.each_cons(2) do |chunk| p chunkend# >> [1, 2]# >> [2, 3]# >> [3, 4]# >> [4, 5]# >> [5, 6]# >> [6, 7]# >> [7, 8]# >> [8, 9]