From: matt@... (matt neuburg) Date: 2009-06-08T01:40:07+09:00 Subject: Re: adding, multiplying array Rick DeNatale wrote: > On Sun, Jun 7, 2009 at 10:15 AM, Haris > Bogdanovi? wrote: > > Hi. > > > > I want to multply all elements of two arrays and add that to all elements of > > the third array like this: > > > > c+=a*b > > > > c=[1,1,1] > > a=[2,2,2] > > b=[3,3,3] > > > > c=[7,7,7] # (1+2*3)=7 > > > > I tried (found on google): > > > > a.zip(b).map {|i,j| i*j} (don't really know how that works) > > zip weaves two enumerables together and creates a new enumerable: > > a.zip(b) # => [[2, 3], [2, 3], [2, 3]] > > [[2, 3], [2, 3], [2, 3]].map {|i,j| i*j} > > takes each sub-array, multiplies the two elements and returns a new > array with the products which produces [6, 6, 6] > > > > > and how to add that to c array ? > > > > Just use zip and map again with a block which adds the elements. > > c = c.zip(a.zip(b).map {|i, j| i*j}).map {|i, j|i + j} > > Which changes the variable c to reference a new array which turns out > to be [7, 7, 7] And if you're going to be doing this kind of thing a lot, you might like to generalize the repeated zip -> map operation: class Array def combine(other, method) zip(other).map {|x,y| x.send(method,y)} end end c = [1,1,1] a = [2,2,2] b = [3,3,3] c = a.combine(b, :*).combine(c, :+) #=> [7,7,7] :) I'm sure there's a cleaner way... m. -- matt neuburg, phd = matt@tidbits.com, http://www.tidbits.com/matt/ Leopard - http://www.takecontrolbooks.com/leopard-customizing.html AppleScript - http://www.amazon.com/gp/product/0596102119 Read TidBITS! It's free and smart. http://www.tidbits.com