Ruby 如何在n个元素的重叠组中迭代数组?

Ruby 如何在n个元素的重叠组中迭代数组?,ruby,arrays,loops,methods,Ruby,Arrays,Loops,Methods,假设您拥有此阵列: arr = w|one two three| 如何通过将两个连续元素作为块参数进行迭代,如下所示: 1st cycle: |nil, 'one'| 2nd cycle: |'one', 'two'| 3rd cycle: |'two', 'three'| 到目前为止,我只带了这个: arr.each_index { |i| [i - 1 < 0 ? nil: arr[i - 1], arr[i]] } arr.each|u索引{i|[i-1

假设您拥有此阵列:

arr = w|one two three|
如何通过将两个连续元素作为块参数进行迭代,如下所示:

1st cycle: |nil, 'one'|
2nd cycle: |'one', 'two'|
3rd cycle: |'two', 'three'|
到目前为止,我只带了这个:

arr.each_index { |i| [i - 1 < 0 ? nil: arr[i - 1], arr[i]] }
arr.each|u索引{i|[i-1<0?nil:arr[i-1],arr[i]}

有更好的解决办法吗?是否有类似于
each(n)
?您可以添加
nil
作为
arr
的第一个元素,并使用以下方法:


(我在这里使用
map
来显示每次迭代返回的确切内容)

这正是我想要的。我肯定会有这样的事,我只是不知道而已。谢谢:)很好。但可能不会更改原始数组<代码>([nil]+arr)。每个常数(2)
arr.unshift(nil).each_cons(2).map { |first, second| [first, second] }
# => [[nil, "one"], ["one", "two"], ["two", "three"]]
> [1, 2, 3, 4, 5, 6, 7, 8, 9].each_cons(2).to_a
# => [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]