4

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]
Kyle Decot
  • 20,715
  • 39
  • 142
  • 263

2 Answers2

10
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]]
toro2k
  • 19,020
  • 7
  • 64
  • 71
1

This works, not sure if it is the shortest:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = a.slice(1,a.count)
 => [2, 3, 4, 5, 6, 7, 8, 9, 10]
a.zip(b)
 => [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 10], [10, nil]]

Edited: It is not the shortest. each_cons was made for this task, although the task gets more interesting if you want to have a specific behaviour for longer slices. each_cons(3) won't give you control on the amount of overlap, and my answer cannot deal with longer slices at all.

Neil Slater
  • 26,512
  • 6
  • 76
  • 94