【问题标题】:How to iterate over an array in overlapping groups of n elements? [duplicate]如何在重叠的 n 个元素组中迭代数组? [复制]
【发布时间】:2015-02-02 02:05:09
【问题描述】:

假设你有这个数组:

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)之类的吗?

【问题讨论】:

    标签: ruby arrays loops methods


    【解决方案1】:

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

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

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

    【讨论】:

    • 这正是我想要的。我确定有类似的东西,我只是不知道。谢谢你:)
    • 不错。但可能不会更改原始数组。 ([nil] + arr).each_const(2)
    【解决方案2】:
    > [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]]
    

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      • 1970-01-01
      • 2013-04-27
      • 2011-12-31
      • 1970-01-01
      • 2015-02-24
      相关资源
      最近更新 更多