From: Stefano Crocco Date: 2007-10-04T20:04:23+09:00 Subject: Re: (Newbie) Override * on Array Alle giovedì 4 ottobre 2007, Mike Ho ha scritto: > Hi, > > I've written a simplistic override of the * operator for Arrays so that > [2,4,6]*[2,2,2] = [4,8,12] > > class Array > > def *(other) > > each_with_index do |x,i| > self[i]= x * other[i] > end > end > > end > > It assumes that the arrays are the same length and no error checking is > done. > > My questions are; is this idiomatic Ruby? > What solution would an experienced Rubyist offer? > How would it be best to handle exceptions when the arrays are of > different dimensions and/or length? > > > Many Thanks > > Mike Usually, operators don't modify the operands, but return a new object with the result. For instance: irb: 001> a1 = [1, 2 ,3] [1, 2, 3] irb: 002> a2 = [4,5] [4, 5] irb: 003> a1 + a2 [1, 2, 3, 4, 5] irb: 004> a1 [1, 2, 3] irb: 005> a2 [4, 5] Your method, instead, modifies the first operand: a1 = [1,2,3] a2= [4,5,6] a3 = a1*a2 p a1 => [4, 10, 18] p a3 => [4, 10, 18] I'd do it this way: class Array def *(other) res = [] each_with_index do |x,i| res[i]= x * other[i] end res end end or require 'generator' class Array def *(other) SyncEnumerator.new(self, other).map{|x, y| x*y} end end Regarding errors, you I think you can check the size of the two array at the beginning of the method and raise TypeError if they're different. I hope this helps Stefano