From: Trans Date: 2007-11-11T07:02:43+09:00 Subject: Re: equivalent injecting implementations? On Nov 10, 10:50 am, "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. Ah. sorry. I missed what you were getting at there. Yea, right off the bat length isn't support, so it would have to apply to Array instead. I was really just curious how they differ in result because they were outputing the same thing when I rand some cases on it. > 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. It's basically the the same, but you don't need to pass the memo back each time. T.