DEV Community

Cover image for Hash default values
Oliver
Oliver

Posted on • Edited on • Originally published at codeandclay.com

Hash default values

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 
Enter fullscreen mode Exit fullscreen mode

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" 
Enter fullscreen mode Exit fullscreen mode

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 => {} 
Enter fullscreen mode Exit fullscreen mode

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

my_hash = Hash.new { |_hash, key| "Value for #{key} not set!" } => {} my_hash[:foo] => "Value for foo not set!" my_hash[:bar] => "Value for bar not set!" 
Enter fullscreen mode Exit fullscreen mode

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"} 
Enter fullscreen mode Exit fullscreen mode

See the ruby docs for more info.

Top comments (0)