33

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??

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
beck03076
  • 3,268
  • 2
  • 27
  • 37
  • possible duplicate of [Is there an algorithm to extract values in duets from an array and operate over them?](http://stackoverflow.com/questions/6075266/is-there-an-algorithm-to-extract-values-in-duets-from-an-array-and-operate-over) – jvnill Mar 28 '13 at 12:52

4 Answers4

63

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]]
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
7

.each_cons does exactly what you want.

[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]]
Dogbert
  • 212,659
  • 41
  • 396
  • 397
6

You almost got it right :)

arr = [1,2,3,4,5,6,7,8,9]
arr.each_cons(2) do |chunk|
  p chunk
end
# >> [1, 2]
# >> [2, 3]
# >> [3, 4]
# >> [4, 5]
# >> [5, 6]
# >> [6, 7]
# >> [7, 8]
# >> [8, 9]
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
1

And if you wanted to implement your own each_cons:

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
cons = 2

0.upto(arr.size - cons) do |i|
  p arr[i, cons]
end

Output:

[1, 2]
[2, 3]
[3, 4]
[4, 5]
[5, 6]
[6, 7]
[7, 8]
[8, 9]
Stefan
  • 109,145
  • 14
  • 143
  • 218