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

4

假设你有以下这个数组:

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]] }

有更好的解决方案吗?是否有类似于each(n)的东西?
2个回答

9
您可以将nil添加为您的arr的第一个元素,并使用Enumerable#each_cons方法:
arr.unshift(nil).each_cons(2).map { |first, second| [first, second] }
# => [[nil, "one"], ["one", "two"], ["two", "three"]]

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

这正是我在寻找的。我确信有这样的东西,只是不知道它的存在。谢谢 :) - Alexander Popov
1
很好,但可能不会改变原始数组。([nil] + arr).each_const(2) - SHS

5
> [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]]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接