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

Hash defaults

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 { |_hash, key| "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.

If you really want to get to grips with Ruby development and gain a solid understanding of Object Oriented Design, I thoroughly recommend Sandi Metz's Practical Object Oriented Design in Ruby. It's the perfect introduction to OOP and pragmatic Ruby. You can buy it here.

“Meticulously pragmatic and exquisitely articulate, Practical Object Oriented Design in Ruby makes otherwise elusive knowledge available to an audience which desperately needs it. The prescriptions are appropriate both as rules for novices and as guidelines for experienced professionals.”

Katrina Owen, Creator, Exercism

Essential Reading: Learn Rails 6