From: Rick DeNatale Date: 2007-11-11T23:50:03+09:00 Subject: Re: equivalent injecting implementations? On Nov 10, 2007 4:23 PM, Ezra Zygmuntowicz wrote: > > > On Nov 10, 2007, at 7:50 AM, Rick DeNatale wrote: > > 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. > > > injecting is similar to returning in rails. >There is a common pattern > of accumulating a hash via inject that looks like this: > > [1,2,3].inject({}) { |memo,n| memo[n] = n ; memo} > #=> {1=>1, 3=>3,2=>2} > > Note the ugly trailing ;memo, this is so the fll accumulated hash is > the final return result. > > injecting is just a little bit nicer way to do the same thing: > > [1,2,3].injecting({}) { |memo,n| memo[n] = n } > #=> {1=>1, 3=>3,2=>2} Yes, I suspected that this was what Trans was trying to do, but since the second proposed 'maybe equivalent' implementation didn't seem to be doing the same thing, I was probing for what he really wanted. Having said that, and played a bit with the concept. I'm not sure how useful an injecting method (at least with that name is). As Robert Klemme points out, it breaks depending on what you are injecting. And it's subject to "cargo culting." module Enumerable def injecting(obj, &blk) inject(obj) { |mem, var| yield(mem, var); mem } end end As Ezra points out: [1,2,3].inject({}) { |memo,n| memo[n] = n ; memo} # => {1=>1, 2=>2, 3=>3} [1,2,3].injecting({}) { |memo,n| memo[n] = n} # => {1=>1, 2=>2, 3=>3} But this only works because the block has a side-effect on the memo object. And yes, in cases like this each instead of inject will have the same side effects. [1,2,3].inject(0) { |memo,n| memo + n} # => 6 [1,2,3].injecting(0) { |memo,n| memo + n} # => 0 Here's where the cargo cult danger comes in. Someone who comes across 'injecting' without understanding it might run into things like this. So while the idea of an injecting method seems nice, I'm not enamored of the name. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/