2007/10/4, Mike Ho <mike_houghton / xyratex.com>: > 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? No. (see Stefano's reply) > What solution would an experienced Rubyist offer? irb(main):002:0> require 'enumerator' => true irb(main):003:0> a1=[1,2,3] => [1, 2, 3] irb(main):004:0> a2=[4,5,6] => [4, 5, 6] irb(main):005:0> a3=a1.to_enum(:zip, a2).map {|x,y| x*y} => [4, 10, 18] > How would it be best to handle exceptions when the arrays are of > different dimensions and/or length? If the second array is shorter, you get automatic checking: irb(main):008:0> (a1+[111]).to_enum(:zip, a2).map {|x,y| x*y} TypeError: nil can't be coerced into Fixnum from (irb):10:in `*' from (irb):10 from (irb):10:in `map' from (irb):10:in `each' from (irb):10:in `zip' from (irb):10:in `each' from (irb):10:in `map' from (irb):10 from :0 In the other case the result array just has the length of the first array: irb(main):009:0> a1.to_enum(:zip, a2+[111]).map {|x,y| x*y} => [4, 10, 18] Depends on what you want to do what kind of error checking you need. Kind regards robert