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