我必须同时遍历两个不同的数组。假设我有两个这样的数组:
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
循环遍历一个数组,并使用当前索引在另一个数组中获取所需的元素:
a1.each_with_index do |a, i|
puts "#{a},#{a2[i]}"
end
通常的方法是使用zip
:
zip(arg,...)→new_ary zip(arg,...){| arr |阻止}→无
将任何参数转换为数组,然后将
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
a1 = *?a..?d
a2 = *?e..?h
a1.zip(a2).map { |e| puts e.join ?, }
a,e
b,f
c,g
d,h