From: Robert Klemme Date: 2008-10-01T23:03:31+09:00 Subject: Re: Mode method for Array 2008/10/1 David A. Black : > Hi -- > > On Wed, 1 Oct 2008, Robert Klemme wrote: > >> 2008/10/1 Erik Veenstra : >>> >>> Speed is also the reason for "pre-defining" variables used in >>> iterations. (6% faster!!) >> >> Premature optimization IMHO. > > As much as I like inject, I have to say I've always felt that the ones > that look like this: > > inject({}) {|h,item| do_something; h } > > are kind of unidiomatic. Evan Phoenix was saying recently on IRC (I > hope I'm remembering/quoting correctly) that his rule of thumb was > that inject was for cases where the accumulator was not the same > object every time, and that where a single object is having elements > added to it, an each iteration from the source collection was better. In that case #map might be more appropriate - at least if the target collection is an Array. Btw, did we ever discuss having #map accept a parameter which defaults to []? i.e. module Enumerable def map(target = []) each {|x| target << yield x} target end end > I tend to agree, though I'm not able to come up with a very technical > rationale. > > What say you, oh inject king? Um..., I kind of agree about the unidiomaticness. It's ugly. These are certainly much nicer inject(0) {|h,item| item + h } inject("") {|s,item| s << item } I have to admit I use it sparingly these days. :-) Kind regards robert -- remember.guy do |as, often| as.you_can - without end