【问题标题】:Ruby array each_slice_with_index?Ruby数组each_slice with_index?
【发布时间】:2011-08-24 10:44:51
【问题描述】:

如果我有arr = [1, 2, 3, 4],我知道我可以执行以下操作...

> arr.each_slice(2) { |a, b| puts "#{a}, #{b}" }
1, 2
3, 4

...还有...

> arr.each_with_index { |x, i| puts "#{i} - #{x}" }
0 - 1
1 - 2
2 - 3
3 - 4

...但是有没有内置的方法可以做到这一点?

> arr.each_slice_with_index(2) { |i, a, b| puts "#{i} - #{a}, #{b}" }
0 - 1, 2
2 - 3, 4

我知道我可以构建自己的并将其粘贴到数组方法中。只是看看是否有内置函数可以做到这一点。

【问题讨论】:

    标签: ruby iteration built-in


    【解决方案1】:

    像大多数迭代器方法一样,each_slice 自 ruby​​ 1.8.7+ 起在没有块的情况下调用时返回一个可枚举,然后您可以在其上调用更多可枚举方法。所以你可以这样做:

    arr.each_slice(2).with_index { |(a, b), i| puts "#{i} - #{a}, #{b}" }
    

    【讨论】:

    • 非常酷!为了完成我的原始问题,我需要执行 #{i*2} 来获取原始 arr 中的索引,而不是切片枚举中的索引。
    【解决方案2】:
    arr.each_slice(2).with_index { |(*a), i| ...
    

    还要注意,数组,block的第一个参数,可以是*arr

    【讨论】:

      【解决方案3】:

      在 1.9 中,如果没有提供块,很多方法都会返回一个枚举器。您可以在枚举器上调用另一个方法。

      arr = [1, 2, 3, 4, 5, 6, 7, 8] 
      arr.each_with_index.each_slice(2){|(a,i), (b,j)| puts "#{i} - #{a}, #{b}"}
      

      (@sepp2k 的变体)。结果:

      0 - 1, 2
      2 - 3, 4
      4 - 5, 6
      6 - 7, 8
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-07
        • 1970-01-01
        • 2012-11-14
        • 1970-01-01
        • 2010-11-30
        • 2011-08-31
        • 1970-01-01
        • 2016-04-08
        相关资源
        最近更新 更多