如何同时在 ruby 中迭代两个数组,我不想使用 for 循环。例如这是我的数组=
array 1=["a","b","c","d"]
array 2=[1,2,3,4]
例如,您可以像这样使用 zip 功能:
array1.zip(array2).each do |array1_var, array2_var|
## whatever you want to do with array_1var and array_2 var
end
您可以使用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
您可以zip
将它们放在一起,然后使用each
.
array1.zip(array2).each do |pair|
p pair
end
如果两个数组的大小相同,您可以执行以下操作:
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
假设两个数组的大小相同,您可以使用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
当两个数组的大小相同时,您可以执行以下操作:
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
必须调用。