From: Ross Bamford Date: 2006-03-30T00:32:17+09:00 Subject: Re: How to interator over two arrays? On Thu, 2006-03-30 at 00:18 +0900, baumanj@gmail.com wrote: > I don't see how this is an alternative for inject; it's just a > different need. You use map when you want to generate a new Enumerable > and inject when you want to generate a single value. The answer to the > question "how does one iterate over multiple collections in parallel?" > is just to use zip and the fact that assignment of an array to multiple > variables puts the values of the elements into the variables. > Glad you top posted this one, makes it easy to quote the original post: > Ross Bamford wrote: > > On Wed, 2006-03-29 at 13:28 +0900, brez! !! wrote: > > > > > I'm looking for a way to iterate over two arrays and sum or multiply or > > > whatever each element resulting in a new array of the summed elements, > > > e.g. > > > > > > a[0]+b[0], a[1]+b[1], ... a[n]+b[n] > > Notice OP wanted to sum or multiply each element *resulting in a new array of summed elements*. Other solutions posted injected an array: arr.zip(brr).inject([]) { |ary,(a,b)| ary << a + b } And I was just generally commenting that any time you inject an array and want a one-for-one transformation you can avoid that and use map. I obviously didn't mean that #map is a general-purpose alternative to #inject... > > Just a footnote to the other solutions you have for this, you can avoid > > inject to make it a bit shorter using map (thanks to the way block > > argument assignment works with arrays): > > > > ary = [1,2,3,4,5] > > # => [1, 2, 3, 4, 5] > > > > bry = ary.dup > > # => [1, 2, 3, 4, 5] > > > > ary.zip(bry).map! { |a,b| a+b } > > # => [2, 4, 6, 8, 10] > > > > -- > > Ross Bamford - rosco@roscopeco.REMOVE.co.uk -- Ross Bamford - rosco@roscopeco.REMOVE.co.uk