11

Given this Ruby array:

[1, 2, 3, 4, 5]

What is the easiest way to iterate it like this?

[[1,2], [2,3], [3,4], [4,5]]

Or this?

[[1,2,3], [2,3,4], [3,4,5]]
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Jostein
  • 3,124
  • 1
  • 22
  • 27

1 Answers1

21

each_cons (docs) does this. You just pass it the size of the chunks you want and it will yield them to the block you pass.

If you actually want the arrays, then you can of course chain this with to_a, for example

(1..5).each_cons(3).to_a
Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174