From: Joel VanderWerf Date: 2001-10-06T03:47:43+09:00 Subject: [ruby-talk:22137] Re: Possible to iterate on two enumerables together? Paul Brannan wrote: > > On Sat, 6 Oct 2001, Phil Mitchell wrote: > > > If I have two enumerables, is there a ruby way to connect them? That > > is, I want to march through the two collections and operate on pairs > > of items. The best I came up with was to convert each one to an array > > and then iterate on the index. > > Yes, this is possible using a number of methods: > 1) Convert the two enumerables to arrays using to_a, each, or collect, > then iterator over the arrays using the [] operator and an index. > 2) Use some other form of random-access to "iterate" through each > enumerable. > 3) Use a continuation to "continue" iteration through each enumerable. Or threads, which probably has the same tradeoffs as continuations. This is described in the FAQ: http://www.rubycentral.com/faq/rubyfaq-5.html#ss5.5 One approach to array conversion is at: http://redshift.sourceforge.net/enum/op.html The syntax is slightly better than manual conversion: for x, y, z in product enum1, enum2, enum3 .... I would guess the generator/synchronizer approach is better for large enumerables (so you don't have to generate large arrays), or enumerables that have side effects to their enumeration (so maybe you don't want to evaluate enum1.to_a, and then enum2.to_a, etc.). -- Joel VanderWerf California PATH, UC Berkeley mailto:vjoel@path.berkeley.edu Ph. (510) 231-9446 http://www.path.berkeley.edu FAX (510) 231-9512