Given that I have the array [1,2,3,4,5,6,7,8,9,10]
what is the shortest way to grab a slice of 2 elements at a time while making sure that there is an overlap between each slice. For example:
Expected result
[1,2]
[2,3]
[3,4]
[4,5]
[5,6]
[6,7]
[7,8]
[8,9]
[9,10]
[10,nil]
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
(a + [nil]).each_cons(2).to_a
# => [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7],[7, 8], [8, 9], [9, 10], [10, nil]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With