Given the array: [1,2,3,4]
I would like to receive an array back of [[1,2],[2,3],[3,4]]
.
Is there a one-liner or a method that does this?
Given the array: [1,2,3,4]
I would like to receive an array back of [[1,2],[2,3],[3,4]]
.
Is there a one-liner or a method that does this?
You can use Enumerable#each_cons, passing 2 as argument:
[1, 2, 3, 4].each_cons(2).to_a
# [[1, 2], [2, 3], [3, 4]]
You need to use to_a
there, because each_cons by itself returns an Enumerator object.