From: Leslie Viljoen Date: 2008-02-21T00:56:52+09:00 Subject: Re: ||= [] idiom On Feb 20, 2008 11:44 AM, Robert Klemme wrote: > 2008/2/19, MenTaLguY : > > > On Wed, 20 Feb 2008 07:15:52 +0900, Sebastian Hungerecker wrote: > > >> .. is there a better way? > > > > > > @categories = Hash.new {Array.new} > > > pagelist.each do |resource| > > > @categories[resource.tag] << resource > > > end > > > > Although it is specific to hashes, when this is applicable I do > > think it can be a better approach than the more general approach > > I outlined in my other email. > > But it needs the fix Joel pointed out: > > @categories = Hash.new {|h,k| h[k] = []} > > Theoretically this could even be more efficient than > > (@categories[k] ||= []) << v > > because the check is done only once per missing key. A benchmark does indeed show it to be faster, though you need truly huge arrays to see the difference.