From: Robert Klemme Date: 2009-02-07T22:18:01+09:00 Subject: Re: Special Hash Constructors On 07.02.2009 11:26, Trans wrote: > > On Feb 6, 12:09 pm, 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 > > I've been using the name #autonew for this last one. > > Also @Tom Link > > def Hash.with(default=nil) > begin > new { | h, k | h[k] = default.dup } > rescue TypeError > new(default) # same as { | h, k | h[k] = default } > end > end Where's the point of the rescue clause? The error will show up much later, i.e. after the method has returned. Also, as Tom pointed out, this is not the same as what I proposed - not even similar. Regards robert