2011-01-27 16 views
6

Qual è il modo migliore (bellezza ed efficienza in termini di prestazioni) per eseguire iterazioni su più array in Ruby? Diciamo che abbiamo un array:Il modo migliore per scorrere su più array?

a=[x,y,z] 
b=['a','b','c'] 

e voglio questo:

x a 
y b 
z c 

Grazie.

+0

possibile duplicato del [Qual è la 'via Ruby' per scorrere su due matrici in una sola volta] (http://stackoverflow.com/questions/3580049/whats-the-ruby-way-to-iterate-over -due-array-at-once) – Vache

risposta

3

Procedimento zip su oggetti array:

a.zip b do |items| 
    puts items[0], items[1] 
end 
+3

Si potrebbe anche qualcosa di simile a 'a.zip (b) {| first, second | p [first, second]} 'invece di indicizzare' items'. –

2
>> a=["x","y","z"] 
=> ["x", "y", "z"] 
>> b=["a","b","c"] 
=> ["a", "b", "c"] 
>> a.zip(b) 
=> [["x", "a"], ["y", "b"], ["z", "c"]] 
>> 
6

Un'alternativa utilizza each_with_index. Un rapido benchmark mostra che questo è leggermente più veloce rispetto all'uso di zip.

a.each_with_index do |item, index| 
    puts item, b[index] 
end 

Benchmark:

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 

Risultati:

 user  system  total  real 
ewi 7.890000 0.000000 7.890000 ( 7.887574) 
zip 10.920000 0.010000 10.930000 (10.918568) 
+0

Era sotto MRI (1.8) o YARV (1.9)? –

+0

ruby ​​1.9.2p136 (2010-12-25 revisione 30365) [x86_64-darwin10.6.0] –

1

mi piace usare trasposta quando iterazione attraverso array multipli utilizzando Ruby. Spero che questo ti aiuti.

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 
Problemi correlati