From: "Peña, Botp" Date: 2006-07-05T12:44:01+09:00 Subject: Re: Parallel Array 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). Zip allows any number of arrays. so now we have to keep track of how many arrays we are zipping. irb(main):002:0> a=[1,2,3] => [1, 2, 3] irb(main):003:0> b=[4,5,6] => [4, 5, 6] irb(main):004:0> c=[7,8,9] => [7, 8, 9] irb(main):005:0> a.zip(b).map{|x,y| x + y } => [5, 7, 9] irb(main):007:0> a.zip(b,c).map{|x,y,z| x + y + z } => [12, 15, 18] Maybe, we just create a Array#sum to simplify and scale further, like so, 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. # Not as fast as the Array.new(size) version, but the block doesn't need # to know which arrays it's operating on. and no length/size pre-det, too :) # BTW, does anyone know why zip with a block returns nil? It would be # handy to have it map. maybe, ruby is trying to tell us beware. if we screw our block, we might get bloated run-away arrays. maybe we should map to be sure... kind regards -botp # Regards, # Sean