From: Stefano Crocco Date: 2007-10-05T03:32:40+09:00 Subject: Re: (Newbie) Override * on Array Alle giovedì 4 ottobre 2007, Mike Ho ha scritto: > Stefano Crocco wrote: > > 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 > > Thanks for the replies guys. > > The SyncEnumerator looks elegant but when I tried it I got the following > error > > in `*': undefined method `*' for nil:NilClass (NoMethodError) > > for the line > > SyncEnumerator.new(self, other).map{|x, y| x*y} > > > I call the method by... > > a1=[2, 4, 6] > a2= [2, 2, 2] > > puts a1*a2 > > I put some debug in like this > > def *(other) > SyncEnumerator.new(self, other).map do |x,y| > puts "x #{x} y #{y}" > x*y > end > end > > and the output I get is this > x 2 y 2 > x 4 y 2 > x 6 y 2 > x y > C:/ruby_work/test/scratch.rb:23:in `*': undefined method `*' for > nil:NilClass (NoMethodError) > So it seems to 'run off the end' > > Any thoughts ? > > Thanks This is strange. It works correctly for me: require 'generator' class Array def *(other) SyncEnumerator.new(self, other).map{|x, y| x*y} end end a1 = [2,4,6] a2 = [2,2,2] puts a1*a2 => 4 8 12 I can't understand why it isn't working for you. Stefano