From: Robert Klemme Date: 2006-03-07T06:54:08+09:00 Subject: Re: What is the best way to iterate through two containers of the same length? 2006/3/6, Mark Watson : > 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| .... } > > I thought of writing my own iterator class so that I could do something > like: > > Iterator.new(c1,c2).each {|x1,x2| .... } > > but that looks clumsy and inefficient. > > I am transitioning to using mostly Ruby (moving away from Java, Lisp, > and Smalltalk) and I would like to use the proper Ruby idioms. If the two are arrays you can use Array#zip: >> %w{foo bar baz}.zip([1,2,3]) {|a,b| print a, "-", b,"\n"} foo-1 bar-2 baz-3 For the more general case you can look at Generator http://ruby-doc.org/stdlib/libdoc/generator/rdoc/ Kind regards robert -- Have a look: http://www.flickr.com/photos/fussel-foto/