From: Armin Armbruster Date: 2008-11-08T05:52:47+09:00 Subject: Re: How to operate on 2 arrays simultaneously? I just ran into a similar problem, and I thought it fits into this thread. The Vector class defines the collect2() and collect2!() methods, which conceptually I like very much. So I thought I could just use the same concept and extend Array like this: class Array def collect2(v) # :yield: e1, e2 Array.Raise ErrDimensionMismatch if size != v.size (0 .. size - 1).collect do |i| yield self[i], v[i] end end def collect2!(v) # :yield: e1, e2 Array.Raise ErrDimensionMismatch if size != v.size (0 .. size - 1).collect do |i| self[i] = yield self[i], v[i] end end end After this I can simply do: a = [1,2,3] b = [4,5,6] a.collect2(b){|e1,e2| e1+e2} => [5, 7, 9] Does anybody see anything wrong with this? If not, it seems such a handy concept that I'm surprised these are not standard methods of Array. I've had this problem in various forms over the past and typically reverted to Array#each_index, always thinking that this is too clumsy for Ruby, but until now I never took the time to come up with something more elegant (not that I want to take any credit for this suggestion as I simply copied what's already in Vector). Todd Benson wrote: > On Thu, Sep 11, 2008 at 2:02 PM, Peter Bunyan > wrote: >> >> http://www.ruby-doc.org/stdlib/libdoc/matrix/rdoc/classes/Matrix.html > > Yeah, that's probably what I would do for a simple script. I haven't > checked memory usage, but it is elegant IMHO. Probably best for very > large arrays. > > a = 1, 2, 3, 4 > b = 4, 3, 2, 1 > (Matrix[a] + Matrix[b]).to_a.flatten > > => [5, 5, 5, 5] > > Todd -- Posted via http://www.ruby-forum.com/.