From: Rick DeNatale Date: 2007-11-11T00:50:27+09:00 Subject: Re: equivalent injecting implementations? 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. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/