4

如何同时在 ruby​​ 中迭代两个数组,我不想使用 for 循环。例如这是我的数组=

array 1=["a","b","c","d"]
array 2=[1,2,3,4]
4

6 回答 6

8

例如,您可以像这样使用 zip 功能:

array1.zip(array2).each do |array1_var, array2_var|
 ## whatever you want to do with array_1var and array_2 var 
 end
于 2013-09-28T03:42:31.830 回答
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
于 2013-09-28T03:42:46.227 回答
1

您可以zip将它们放在一起,然后使用each.

array1.zip(array2).each do |pair|
  p pair
end
于 2013-09-28T03:42:14.650 回答
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
于 2013-09-28T03:42:48.073 回答
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
于 2013-09-28T03:44:17.853 回答
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必须调用。

于 2013-09-28T05:30:07.850 回答