From: Robert Klemme Date: 2004-08-03T17:56:33+09:00 Subject: Re: Request for two methods in Array class "Yukihiro Matsumoto" schrieb im Newsbeitrag news:1091510011.625923.536.nullmailer@picachu.netlab.jp... > Hi, > > In message "Request for two methods in Array class" > on 04/08/03, Mike Hall writes: > > |1. A new method, Array.combine (needs a better name for general use). > | It takes entries from two (or many) arrays and combines them. > | (like a combination of Array.zip, fetch, and map) > > Sounds nice. But I'm not sure "combine" is a proper name for the > method. We need more discussion, for example: > > * the best name for the behavior. I like "combine" but I'm open to suggestions. > * whether it takes only one argument or any number of arguments. IMHO n>=0 > * whether "multiplication" should be the default. No IMHO. I imageine behavior similar to this: class Array def combine(*arrays, &b) result = [] each_with_index {|e,idx| result << b.call(e, *arrays.map {|ar| ar[idx]})} result end end Note that arrays can contain anything that implements [], which might even be a lambda (aka function): a = [1,2,3] a.combine(lambda {|i| i*2}) {|x,y| x*y} => [0, 4, 12] So "arrays" might not be the ideal argument name. Thinking a bit further about this it seems to me that the method might be better put into Enumerable or Array as module method since arguments seem to be symmetric: class Array def self.combine(*arrays, &b) limit = arrays.inject(0){|l,a| s=a.size; s>l ? s : l} result = Array.new limit limit.times {|i| result[i] = b.call(*arrays.map {|ar| ar[i]}) } result end end irb(main):054:0> Array.combine([1,2,3],[1,3,5]) {|x,y| x*y} => [1, 6, 15] irb(main):055:0> Array.combine([1,2,3],[1,3,5]) {|*x| x.inject(1){|z,i| z*i} } => [1, 6, 15] Kind regards robert