在Ruby中迭代多個數組的最佳方法(美觀和高效的性能)是什麼? 比方說,我們有一個數組:迭代多個數組的最佳方法?
a=[x,y,z]
b=['a','b','c']
,我想這一點:
x a
y b
z c
感謝。
在Ruby中迭代多個數組的最佳方法(美觀和高效的性能)是什麼? 比方說,我們有一個數組:迭代多個數組的最佳方法?
a=[x,y,z]
b=['a','b','c']
,我想這一點:
x a
y b
z c
感謝。
的zip
方法在陣列上的對象:
a.zip b do |items|
puts items[0], items[1]
end
你也可以像`a.zip(b){| first,second | p [first,second]}`而不是索引`items`。 – 2011-01-27 13:47:12
>> a=["x","y","z"]
=> ["x", "y", "z"]
>> b=["a","b","c"]
=> ["a", "b", "c"]
>> a.zip(b)
=> [["x", "a"], ["y", "b"], ["z", "c"]]
>>
一種替代是使用each_with_index
。快速基準測試顯示,這比使用zip稍快。
a.each_with_index do |item, index|
puts item, b[index]
end
基準:
a = ["x","y","z"]
b = ["a","b","c"]
Benchmark.bm do |bm|
bm.report("ewi") do
10_000_000.times do
a.each_with_index do |item, index|
item_a = item
item_b = b[index]
end
end
end
bm.report("zip") do
10_000_000.times do
a.zip(b) do |items|
item_a = items[0]
item_b = items[1]
end
end
end
end
結果:
user system total real
ewi 7.890000 0.000000 7.890000 ( 7.887574)
zip 10.920000 0.010000 10.930000 (10.918568)
這是MRI(1.8)還是YARV(1.9)? – 2011-01-27 22:18:51
我喜歡通過使用Ruby多個陣列迭代時使用轉置。希望這可以幫助。的
bigarray = []
bigarray << array_1
bigarray << array_2
bigarray << array_3
variableName = bigarray.transpose
variableName.each do |item1,item2,item3|
# do stuff per item
# eg
puts "item1"
puts "item2"
puts "item3"
end
可能重複[最新的「Ruby之道」,一次遍歷兩個數組(http://stackoverflow.com/questions/3580049/whats-the-ruby-way-to-iterate-over -two-arrays-at-once) – Vache 2014-09-09 21:05:45