From: Sean O'Halpin Date: 2006-07-05T14:08:59+09:00 Subject: Re: Parallel Array On 7/5/06, Pe�a, Botp wrote: > Sean wrote: > # Botp wrote: > # > i do not go for faster, but maybe simpler to the eye, > # > > # > c=[] > # > a.each_index{|i| c << a[i]+b[i]} > # > > # > kind regards -botp > # > > # I like this: > # > # a.zip(b).map{|(x,y)| x + y} > > Yes, Sean, zip w map is cool, really. (i think you can lose the parens, too). Hmm.. wonder what I was doing there? > Zip allows any number of arrays. so now we have to keep track of how many arrays we are zipping . Good point. [snip zip examples] > Maybe, we just create a Array#sum to simplify and scale further, like so, # here's one way to do it: module Enumerable def sum(initial = 0) inject(initial) { |acc, el| acc + el } end end > > irb(main):016:0> a.zip(b).map{|e| e.sum} > => [5, 7, 9] > irb(main):017:0> a.zip(b,c).map{|e| e.sum} > => [12, 15, 18] > > no change in inside block. ruby is cool. Certainly is :) For example: module Enumerable def zip_map(*args, &block) zip(*args).map( &block ) end end # and with nobu's definition of Symbol#to_proc class Symbol def to_proc Proc.new{|*args| args.shift.__send__(self, *args)} end end # we could do this: a=[1,1,1,1] b=[2,2,2,2] c=[3,3,3,3] p a.zip_map(b, c, &:sum) #=> [6, 6, 6, 6] This isn't particularly fast though! Regards, Sean