What's the 'Ruby way' to iterate over two arrays at once
>> @budget = [ 100, 150, 25, 105 ]=> [100, 150, 25, 105]>> @actual = [ 120, 100, 50, 100 ]=> [120, 100, 50, 100]>> @budget.zip @actual=> [[100, 120], [150, 100], [25, 50], [105, 100]]>> @budget.zip(@actual).each do |budget, actual|?> puts budget>> puts actual>> end1001201501002550105100=> [[100, 120], [150, 100], [25, 50], [105, 100]]
There is another way to iterate over two arrays at once using enumerators:
2.1.2 :003 > enum = [1,2,4].each => #<Enumerator: [1, 2, 4]:each> 2.1.2 :004 > enum2 = [5,6,7].each => #<Enumerator: [5, 6, 7]:each> 2.1.2 :005 > loop do2.1.2 :006 > a1,a2=enum.next,enum2.next2.1.2 :007?> puts "array 1 #{a1} array 2 #{a2}"2.1.2 :008?> endarray 1 1 array 2 5array 1 2 array 2 6array 1 4 array 2 7
Enumerators are more powerful than the examples used above, because they allow infinite series, parallel iteration, among other techniques.