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

时间:2014-12-04 08:59:29

标签: ruby arrays loops methods

说你有这个数组:

arr = w|one two three|

如何通过将两个连续元素作为块参数进行迭代:

1st cycle: |nil, 'one'|
2nd cycle: |'one', 'two'|
3rd cycle: |'two', 'three'|

Sofar我只是来了这个:

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

有更好的解决方案吗?是否有类似each(n)的内容?

2 个答案:

答案 0 :(得分:9)

您可以添加nil作为arr的第一个元素并使用Enumerable#each_cons方法:

arr.unshift(nil).each_cons(2).map { |first, second| [first, second] }
# => [[nil, "one"], ["one", "two"], ["two", "three"]]

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

答案 1 :(得分:3)

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