如何在ruby中同时迭代两个数组,我不想使用for循环。 例如,这是我的数组=
array 1=["a","b","c","d"]
array 2=[1,2,3,4]
答案 0 :(得分:8)
您可以使用zip功能,例如:
array1.zip(array2).each do |array1_var, array2_var|
## whatever you want to do with array_1var and array_2 var
end
答案 1 :(得分:5)
您可以使用Array#zip
(无需使用each
,因为zip
接受可选区块:
array1 = ["a","b","c","d"]
array2 = [1,2,3,4]
array1.zip(array2) do |a, b|
p [a,b]
end
或者,Array#transpose
:
[array1, array2].transpose.each do |a, b|
p [a,b]
end
答案 2 :(得分:1)
您可以zip
将它们放在一起,然后使用each
遍历对。
array1.zip(array2).each do |pair|
p pair
end
答案 3 :(得分:0)
如果两个数组的大小相同,则可以执行以下操作:
array1=["a","b","c","d"]
array2=[1,2,3,4]
for i in 0..arr1.length do
//here you do what you want with array1[i] and array2[i]
end
答案 4 :(得分:0)
假设两个数组的大小相同,您可以使用each_with_index
来迭代它们,使用第二个数组的索引:
array1.each_with_index do |item1, index|
item2 = array2[index]
# do something with item1, item2
end
像这样:
irb(main):007:0> array1.each_with_index do |item1, index|
irb(main):008:1* item2 = array2[index]
irb(main):009:1> puts item1, item2
irb(main):010:1> end
a
1
b
2
c
3
d
4
答案 5 :(得分:0)
当两个阵列具有相同的大小时,您可以执行以下操作:
array1=["a","b","c","d"]
array2=[1,2,3,4]
array2.each_index{|i| p "#{array2[i]},#{array1[i]} at location #{i}"}
# >> "1,a at location 0"
# >> "2,b at location 1"
# >> "3,c at location 2"
# >> "4,d at location 3"
如果一个数组有可能比其他数组大,那么必须调用larger_array#each_index
。