From: James Edward Gray II Date: 2006-03-07T06:54:29+09:00 Subject: Re: What is the best way to iterate through two containers of the same length? On Mar 6, 2006, at 3:48 PM, Mark Watson wrote: > If I have two containers c1 and c2 of the same length, what is the > proper "Ruby way" to do this: > > c1.length.times {|i| > # access c1[i], c2[i] > } > > I like that Ruby container classes provide their own iterators, but > what I would like to have is something like: > > (c1,c2).each {|x1,x2| .... } You are looking for Enumerable#zip: >> letters = %w{A B C} => ["A", "B", "C"] >> numbers = [1, 2, 3] => [1, 2, 3] >> letters.zip(numbers) do |letter, number| ?> puts "#{letter}#{number}" >> end A1 B2 C3 => nil You can also use the standard generator library to turn Ruby's internal iterators into external iterators (like Java's iterators) if needed. Hope that helps. James Edward Gray II