From: James Gray Date: 2009-02-07T00:40:05+09:00 Subject: Re: iterating over two arrays simultaneously On Feb 6, 2009, at 9:24 AM, Jean-Denis Muys wrote: > James' solution to the previous question being so much better than > mine (which I did for my learning purposes), I think your solution was just fine. > I dare asking about how to iterate over two arrays in parallel. I > don't see a way to use the iteration methods, and my solution below > doesn't feel idiomatic at all: > > array1 = [1, 2, 3] > array2 = ["one", "two", "three"] > # note: both arrays are known to be the same size > > (0..array1.size-1).each { > | i | > print "#{array2[i]} = #{array1[i]}\n" > } Here's one way: >> array1 = (1..3).to_a => [1, 2, 3] >> array2 = %w[one two three] => ["one", "two", "three"] >> array1.zip(array2) { |num, word| puts "#{num} #{word}" } 1 one 2 two 3 three => nil and another: >> require "generator" => true >> SyncEnumerator.new(array1, array2).each { |num, word| puts "#{num} #{word}" } 1 one 2 two 3 three => #, cont_yieldnil, queue[], block#, cont_next#, #, cont_yieldnil, queue[], block#, cont_next#] Hope that helps. James Edward Gray II