Ruby hashes: defaults and overrides
Using variable length keyword arguments to vary a default hash
A neat trick to return hashes with default values and easy overrides using variable length keyword arguments.
Let's imagine I want a hash which has:
- A default set of key-values
- Able to override any of the key-values
- Able to add new key-values
This is pretty easy with a Hash#merge
but there is a cute other way using keyword arguments and the **
expansion operator.
def hash_with_defaults(**hash_overrides)
{
foo: 'foo',
bar: 'bar',
**hash_overrides
}
end
pp hash_with_defaults
#=> {:foo=>"foo", :bar=>"bar"}
pp hash_with_defaults(foo: 'xxx')
#=> {:foo=>"xxx", :bar=>"bar"}
pp hash_with_defaults(foo: 'xxx', baz: 'zzz')
#=> {:foo=>"xxx", :bar=>"bar", :baz=>"zzz"}
Member discussion