From: "rosenfeld (Rodrigo Rosenfeld Rosas)" Date: 2012-06-25T21:24:37+09:00 Subject: [ruby-core:45832] [ruby-trunk - Feature #6641] Hash.auto constructor Issue #6641 has been updated by rosenfeld (Rodrigo Rosenfeld Rosas). Maybe something like Hash.with_default{[]}. "with_default" could be both a class and an instance method so that you could have something like {a: 1, b: 2}.with_default(0).merge... It would always return the hash itself... Groovy has a I guess that's how default values work in Groovy (not quite the same behavior). In Groovy you can define default values as [:].withDefault{0}. You can optionally use the block argument as the key. So I guess it would be great if Ruby with_default supported all those syntax below: Hash.with_default(0) Hash.with_default{Time.now} Hash.with_default{|k| k.to_sym} {}.with_default(0) {}.with_default{Time.now} {}.with_default{|k| k.to_sym} ---------------------------------------- Feature #6641: Hash.auto constructor https://bugs.ruby-lang.org/issues/6641#change-27408 Author: trans (Thomas Sawyer) Status: Open Priority: Normal Assignee: Category: core Target version: 2.0.0 =begin It is not uncommon to need a Hash following the pattern: Hash.new{ |h,k| h[k]={} } Another common example: Hash.new{ |h,k| h[k]=[] } This is common enough that it would very nice if we could have a more concise form, e.g. Hash.auto{ {} } Or for the second example: Hash.auto{ [] } Pure Ruby implementation is pretty simple: def Hash.auto Hash.new{ |h,k| h[k] = yield } end I think it would be nice to have in Core. This is secondary, but it just occurred to me. Could there even be a literal notation for the above? Something like: {}([]) ? =end -- http://bugs.ruby-lang.org/