1 min read

Ruby hashes: defaults and overrides

Using variable length keyword arguments to vary a default hash
Ruby hashes: defaults and overrides
Photo by Glen Carrie / Unsplash

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:

  1. A default set of key-values
  2. Able to override any of the key-values
  3. 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"}