From: Robert Dober Date: 2008-04-19T01:33:28+09:00 Subject: Re: Naming question On Fri, Apr 18, 2008 at 6:04 PM, Sean O'Halpin wrote: > On Fri, Apr 18, 2008 at 12:10 PM, Rick DeNatale wrote: > > > > Which, I believe, first showed up in Rails sometime in 2006. > > > > -- > > Rick DeNatale > > > > Florian Gross published a version in Jan 2005: > http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/4311 module Enumerable def group_by result = Hash.new { |h, k| h[k] = Array.new } self.each do |item| group = yield(item) result[group] << item end return result end end This is the code of the post linked to above, as one can see it works, not as mine above :) but this natural way to write it is quite inefficient as the Facets version shows. I have benchmarked them and to my surprise and that of many others I guess the Facets implementation is almost twice as fast - for many different keys at least result = {} each do | ele| ( result[ yield(ele) ] ||= [] ) << ele end result. Does anybody have the faintest idea why Hash.new{|h,k| ... } is so inefficient? BTW I am quite happy that #group_by is quasi a standard name for this. Cheers Robert -- http://ruby-smalltalk.blogspot.com/ --- Whereof one cannot speak, thereof one must be silent. Ludwig Wittgenstein