From: Robert Klemme Date: 2007-11-11T01:45:04+09:00 Subject: Re: equivalent injecting implementations? On 10.11.2007 16:50, Rick DeNatale wrote: > On Nov 10, 2007 9:37 AM, Trans wrote: >> >> On Nov 10, 8:50 am, "Rick DeNatale" wrote: >>> On 11/9/07, Trans wrote: >>> >>> >>> >>>> Are these strictly equivalent? I get the feeling no, but I haven't >>>> been able to demonstrate it yet. >>>> def injecting(s) >>>> inject(s) do |k, i| >>>> yield(k, i); k >>>> end >>>> end >>>> def injecting(res, &block) >>>> ([res]*length).zip(to_a).each(&block) >>>> res >>>> end >>>> Thanks, >>>> T. >>> I can't see how in general they can be. >>> >>> In which class or module are you defining these? Since you are using >>> inject and each, I'm guessing that it's either Enumerable or some >>> subclass, >>> >>> But then depending on which subclass you don't have a length method so... >>> >>> Perhaps some more context would help. >> Oh sorry, I meant to put that. These are Enumerable methods. >> > module Enumerable > def injecting(s) > inject(s) do |k, i| > yield(k, i); k > end > end > > def injecting2(res, &block) > ([res]*length).zip(to_a).each(&block) > res > end > end > > (1..3).injecting(0) {|k,i| k + i} # => 0 > (1..3).injecting2(0) {|k,i| k + i} # => > # ~> -:9:in `injecting2': undefined local variable or method `length' > for 1..3:Range (NameError) > # ~> from -:15 > > Which illustrates my point. > > Just what is injecting supposed to mean anyway? The first > implementation uses inject and takes a two argument block like inject > does, but seems to be going out of it's way to disregard the value of > the argument block. > > This doesn't seem much like inject to me. Even if you do use it on an Array the two are not equivalent since the second variant does not propagate the block result. The second variant works only when you only modify something (say a Hash). I don't see the point in having the first one since it reimplements #inject - but without the subtle specialty of different behavior when no args are passed to it. Kind regards robert