From: Matthew Smillie Date: 2006-07-05T09:50:46+09:00 Subject: Re: Parallel Array On Jul 5, 2006, at 1:16, Nasir Khan wrote: > If I have two arrays a=[1,1,1,1] and b=[2,2,2,2] and I want to add > each > element up, something like - > > c = a plus b => [3,3,3,3] > > One way I could think up is - > > irb(main):010:0> (0...a.length).collect{|k| a[k]+b[k]} > => [3, 3, 3, 3] > > Is there a better/faster way? This is probably the simplest: # Arrays have constructors too! c = Array.new(a.length) { |i| a[i] + b[i] } These are more fun/complicated. # initialise and fill in place. c = [].fill(0...a.length) { |i| a[i] + b[i] } # use inject, it's good for job security. c = a.zip(b).map { |x| x.inject(0) { |s, n| s + n } } # using inject is fun. Let's do it again. c = (0...a.length).inject([]) { |x, n| x << a[n] + b[n] } I don't think there are any actual efficiency gains to be made, to tell the truth. The direct initialisation is possibly very slightly more efficient (fewer method calls, fewer intermediate arrays created), but I doubt that the difference would be distinguishable from noise in an actual application. The only reason I'm not 100% fond of the block constructor is that its semantics are quite different from the syntactically-similar Hash constructor with a default block, but that's a pretty subjective quibble. matthew smillie.