From: Christopher Dicely Date: 2009-02-07T02:44:28+09:00 Subject: Re: Special Hash Constructors On Fri, Feb 6, 2009 at 9:09 AM, Robert Klemme wrote: > > Hi there, > > we frequently do > > ha = Hash.new {|h,k| h[k] = []} > > so we can later do > > ha[any_key] << anything > > Since the idiom is so common, what does everybody think of putting it into > the standard library: > > def Hash.with_arrays > new {|h,k| h[k] = []} > end > > While we're at it, we might as well add > > def Hash.with_hashes > new {|h,k| h[k] = Hash.new(&h.default_proc)} > end > > Kind regards > > robert Rather than making class methods on Hash to create special hashes like this, why not make subclasses, so you can attach specialized instance methods that make sense only for these kinds of hashes. For instance, for the Hash-of-Hashes form, you might want a method that "rotates" the Hash into a new Hash-of-Hashes like this: def rotate res = HashOfHashes.new each { |ok, ov| ov.each { |ik, iv| res[ik][ok] = iv } } res end