鉴于我有数组[1,2,3,4,5,6,7,8,9,10]
,在确保每个切片之间存在重叠的同时,一次抓取 2 个元素的切片的最短方法是什么。例如:
预期结果
[1,2]
[2,3]
[3,4]
[4,5]
[5,6]
[6,7]
[7,8]
[8,9]
[9,10]
[10,nil]
鉴于我有数组[1,2,3,4,5,6,7,8,9,10]
,在确保每个切片之间存在重叠的同时,一次抓取 2 个元素的切片的最短方法是什么。例如:
预期结果
[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]]
这有效,不确定它是否是最短的:
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]]
编辑:这不是最短的。each_cons
是为此任务而设计的,尽管如果您想对更长的切片具有特定的行为,该任务会变得更有趣。each_cons(3)
不会让您控制重叠量,我的回答根本无法处理更长的切片。