Code & Clay – Notes to self. Mainly Ruby/Rails.

Hash defaults

You can use a pair of empty braces to initialise a hash. But, if you try to access a non-existant key, Ruby returns nil by default.

my_hash = {}
=> {}
my_hash[:foo]
=> nil

Sometimes it might be useful to set a default value. This could be anything: an empty string, a null object, an error…

Here, I’ve set a string as default.

my_hash = {}
=> {}
my_hash.default = "Not set"
=> "Not set"
my_hash[:foo]
=> "Not set"
my_hash[:bar]
=> "Not set"

Now, instead of getting nil for a non-existant entry, I get the default value.

The hash remains empty because I have not created any entries.

my_hash
=> {}

Hash.new accepts a proc which you can use to set default values.

my_hash = Hash.new { "Not set" }
=> {}
my_hash[:foo]
=> "Not set"
my_hash
=> {}

You can also tell the proc to create a new entry if one isn’t found.

my_hash = Hash.new { |hash, key| hash[key] = "Not set" }
=> {}
my_hash[:foo]
=> "Not set"
my_hash[:bar]
=> "Not set"
my_hash
=> {:foo=>"Not set", :bar=>"Not set"}

See the ruby docs for more info.