有没有办法循环遍历两个数组并让它们每次引用某个元素?例如:
first_array = ['a', 'b', 'c', 'd']
second_array = ['e', 'f', 'g', 'h']
first_array.each |item| puts item.get(second_array)
结果看起来像:
a would work with e
b would work with f
c would work with g
d would work with h
我试图这样做,以便当first_array
中的变量传递给second_array
时,它会移动到second_array
中的下一个变量,跳过之前的使用变量。
答案 0 :(得分:8)
那是zip
。
first_array.zip(second_array){|e1, e2| ...}
答案 1 :(得分:2)
你可以这样做:
first_array.each_with_index { |v, i| puts "#{v} can work with #{second_array[i]}" }
# a would work with e
# b would work with f
# c would work with g
# d would work with h
答案 2 :(得分:1)
假设,在您的示例中,两个数组的大小相同,您可以使用Array#transpose:
a1 = %w{a b c d}
#=> ['a', 'b', 'c', 'd']
a2 = %w{e f g h}
#=> ['e', 'f', 'g', 'h']
[a1,a2].transpose { |s1,s2| puts "#{s1} and #{s2}" }
#-> a and e
# b and f
# c and g
# d and h
每当您使用数量相等的数组a
(此处为[a1,a2]
)并希望对每个[a[0][i],a[1][i],..]
操作i
时,您始终可以选择使用transpose
或Array#zip。从某种意义上说,它们是Yin and Yang。
您也可以使用索引:
a1.each_index { |i] puts "#{a1[i]} and #{a2[i]}" }
答案 3 :(得分:0)
给定第二个数组始终至少与第一个数组一样长
first_array.each_with_index |item,index| do
puts "#{item} would work with #{second_array[index]}"
end