From: Phrogz Date: 2007-11-12T00:40:00+09:00 Subject: Re: equivalent injecting implementations? On Nov 10, 1:23 pm, Ezra Zygmuntowicz wrote: > 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. Note that you can avoid the trailing memo with this: [1,2,3].inject({}) { |memo,n| memo.update n=>n } ...but it's a good deal slower: a = (1..10_000).to_a N = 500 require 'benchmark' Benchmark.bmbm{ |x| x.report( 'set' ){ N.times{ a.inject({}){ |memo,n| memo[n] = n; memo } } } x.report( 'update' ){ N.times{ a.inject({}){ |memo,n| memo.update n=>n } } } } Rehearsal ------------------------------------------ set 5.860000 0.010000 5.870000 ( 5.981301) update 11.830000 0.020000 11.850000 ( 11.865100) -------------------------------- total: 17.720000sec user system total real set 5.960000 0.040000 6.000000 ( 6.011882) update 11.850000 0.070000 11.920000 ( 11.925828)