I was writing a rake task to handle importing data from an older community system and needed to set a default value for anything that the old system didn’t have. I was using hashs and thought to myself “It would be sweet if hashs had defaults.” After a quick doc check I found out that hashs do infact support defaults.

I encourage you to check out the Ruby Docs http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-default

Here’s Hash defaults at a quick glance:

h = Hash.new('cat')
h[:not_a_key]         #=> 'cat'

h = {}
h.default = 'cat'
h[:not_a_key]         #=> 'cat'

You can also feed the Hash a block that will execute on lookup

h = Hash.new {|h,k| k+1 }     => {}
h[1]                          => 2
h[2]                          => 3
h[4]                          => 5

h = Hash.new {|h,k| k.to_s + ' says meowww' }  => {}
h[:cat]                                        => 'cat says meowww'

Hashs can also take default Procs. Although as per the docs “It is not possible to set the default to a Proc that will be executed on each key lookup.”

h = {}
h.default = proc do |hash, key|
  hash[key] = key + key
h[2]       #=> #<Proc:0x401b3948@-:6>

To utiize Procs properly you must use the default_proc method:

h.default_proc = proc do |hash, key|
  hash[key] = key + key
h[2]       #=> 4
h["cat"]   #=> "catcat"