【问题标题】:Looping two different array at same time [closed]同时循环两个不同的数组[关闭]
【发布时间】:2014-12-05 01:49:48
【问题描述】:

我必须同时遍历两个不同的数组。假设我有两个这样的数组:

    a1 = ["a","b","c","d"]
    a2 = ["e","f","g","h"]

我想要这样的输出:

    a,e
    b,f
    c,g
    d,h

我试过这个程序,但它打印两个数组两次:

    a1 = ["a","b","c","d"]
    a2 = ["e","f","g","h"]
    a1.each do |a|
    a2.each do |b|
    puts a[0]
    puts b[0]
    end
    end

【问题讨论】:

    标签: ruby-on-rails ruby arrays loops hash


    【解决方案1】:

    通常的方法是使用zip:

    zip(arg, ...) → new_ary
    zip(arg, ...) { |arr|块 } → nil

    将任何参数转换为数组,然后将self 的元素与每个参数的对应元素合并。

    这会生成一系列ary.size n 元素数组,其中n 比参数的数量多一个。

    所以你可以说:

    a1.zip(a2) do |a, b|
      # do things with `a` and `b` in here. `a` will be an element of `a1` and
      # `b` will be the corresponding element of `a2`.
    end
    

    【讨论】:

      【解决方案2】:

      遍历一个数组,并使用当前索引在另一个数组中获取您想要的元素:

      a1.each_with_index do |a, i|
          puts "#{a},#{a2[i]}"
      end
      

      【讨论】:

        【解决方案3】:

        代码

        a1 = *?a..?d
        a2 = *?e..?h
        
        a1.zip(a2).map { |e| puts e.join ?, }
        

        输出

        a,e
        b,f
        c,g
        d,h
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-08
          • 1970-01-01
          • 1970-01-01
          • 2017-02-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多