【问题标题】:Best way to iterate over multiple arrays?迭代多个数组的最佳方法?
【发布时间】:2011-06-16 13:28:19
【问题描述】:

在 Ruby 中迭代多个数组的最佳(美观和高效)方法是什么? 假设我们有一个数组:

a=[x,y,z]
b=['a','b','c']

我想要这个:

x a
y b
z c

谢谢。

【问题讨论】:

标签: ruby arrays loops


【解决方案1】:
【解决方案2】:

数组对象上的zip 方法:

a.zip b do |items|
    puts items[0], items[1]
end

【讨论】:

  • 你也可以像a.zip(b) { |first, second| p [first, second] }这样的东西而不是索引items
【解决方案3】:
>> a=["x","y","z"]
=> ["x", "y", "z"]
>> b=["a","b","c"]
=> ["a", "b", "c"]
>> a.zip(b)
=> [["x", "a"], ["y", "b"], ["z", "c"]]
>>

【讨论】:

    【解决方案4】:

    另一种方法是使用each_with_index。快速基准测试表明,这比使用 zip 稍快。

    a.each_with_index do |item, index|
      puts item, b[index]
    end
    

    基准测试:

    a = ["x","y","z"]
    b = ["a","b","c"]
    
    Benchmark.bm do |bm|
      bm.report("ewi") do
        10_000_000.times do
          a.each_with_index do |item, index|
            item_a = item
            item_b = b[index]
          end
        end
      end
      bm.report("zip") do
        10_000_000.times do
          a.zip(b) do |items|
            item_a = items[0]
            item_b = items[1]
          end
        end
      end
    end
    

    结果:

          user     system      total        real
    ewi  7.890000   0.000000   7.890000 (  7.887574)
    zip 10.920000   0.010000  10.930000 ( 10.918568)
    

    【讨论】:

    • 这是在 MRI (1.8) 还是 YARV (1.9) 下进行的?
    • ruby 1.9.2p136(2010-12-25 修订版 30365)[x86_64-darwin10.6.0]
    【解决方案5】:

    我喜欢在使用 Ruby 遍历多个数组时使用转置。希望这会有所帮助。

    bigarray = []
    bigarray << array_1
    bigarray << array_2
    bigarray << array_3
    variableName = bigarray.transpose
    
    variableName.each do |item1,item2,item3|
    
    # do stuff per item
    # eg 
    puts "item1"
    puts "item2"
    puts "item3"
    
    end
    

    【讨论】:

      猜你喜欢
      • 2012-04-25
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 2011-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多