From: Robert Klemme Date: 2009-09-29T23:59:00+09:00 Subject: Re: Group by unique entries of a hash 2009/9/29 Paul Smith : > On Tue, Sep 29, 2009 at 2:38 PM, Robert Klemme > wrote: >> 2009/9/29 Paul Smith : >>> On Tue, Sep 29, 2009 at 12:43 PM, Ne Scripter >>> wrote: >>> hashMapping = {} >>> >>> IO.foreach(source.to_s) do |data| >>>   fields = data.split(",") >>>   hash = fields[0] >>>   ocrID = fields[1] >>> >>>   hashMapping[ocrID] ||= [] #If hashMapping has never seen this key >>> before, make an empty array >>> >>>   hashMapping[ocrID] << hash #Add the new element to the array for this key >>> >>>  end >> >> It is slightly more efficient to do it in one step: >> >> (hashMapping[ocrID] ||= []) << hash >> >> 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. No, this is defining a hook which is executed each time a key is requested which is not present. In this case the hook stores a new Array in the Hash but you could do other things as well. A default value is defined via Hash.new([]) which does not work in this case for obvious reasons. > I'd also rename the 'hash' variable to 'key' or something, I think > it's less confusing.  Then Your hashMapping can either be given the > name 'hash', because that's what it is, or a name that's actually > useful for describing what the mystical contents of the hash are. Absolutely. I just did not want to cause extra confusion by starting to rename everything. :-) Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/