From: "Jesús Gabriel y Galán" Date: 2009-09-29T23:47:49+09:00 Subject: Re: Group by unique entries of a hash On Tue, Sep 29, 2009 at 4:22 PM, Paul Smith wrote: > On Tue, Sep 29, 2009 at 2:38 PM, Robert Klemme > wrote: >> Even nicer >> >> hashMapping = Hash.new {|h,k| h[k] = []} > > Is this defining a default element for the hash?  I had a vague > recollection you could do this but completely forgot how. Using that constructor you pass a block which will be executed every time there's a missing key. The value of the block is used as a default value, but as it is in this case, it can have the side effect of modifying the hash. If you don't modify the hash inside the block, it's not modified as you can see in the first example: Two examples: irb(main):001:0> h = Hash.new {|h,k| 0} => {} irb(main):002:0> h[:a] => 0 irb(main):003:0> h[:a] += 1 => 1 irb(main):004:0> h => {:a=>1} irb(main):005:0> h2 = Hash.new {|h,k| h[k] = []} => {} irb(main):007:0> h2[:a] => [] irb(main):008:0> h2 => {:a=>[]} Jesus.