From: Rick DeNatale Date: 2009-06-08T00:31:36+09:00 Subject: Re: adding, multiplying array 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] -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale