Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlapping slices in ruby [duplicate]

Tags:

ruby

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]
like image 888
Kyle Decot Avatar asked Dec 21 '22 05:12

Kyle Decot


1 Answers

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]]
like image 78
toro2k Avatar answered Dec 29 '22 22:12

toro2k