From: Trans Date: 2007-11-12T03:39:21+09:00 Subject: Re: equivalent injecting implementations? On Nov 11, 9:50 am, "Rick DeNatale" wrote: > 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. Hmmm... does this mean that the same effect can be achieved with: module Enumerable def inject!(obj) each { |var| yield(obj, var) } obj end end I think the common usecase is simply not having to create the initial object outside the loop statement, eg. obj = 0 each { |i| ... obj ... } so that would make sense. T.