同时循环两个不同的数组

时间:2014-10-10 00:36:36

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

我必须同时遍历两个不同的数组。让我们说我有两个这样的数组:

    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

3 个答案:

答案 0 :(得分:3)

通常的做法是使用zip

  

zip(arg,...)→new_ary
   zip(arg,...){| arr | block}→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

答案 1 :(得分:0)

循环遍历一个数组,并使用当前索引在另一个数组中获取所需的元素:

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

答案 2 :(得分:0)

代码

a1 = *?a..?d
a2 = *?e..?h

a1.zip(a2).map { |e| puts e.join ?, }

输出

a,e
b,f
c,g
d,h
相关问题