Benefits of using `Hash#fetch` over `Hash#[]`

hash, ruby

Solution

Three main uses:

When the value is mandatory, i.e. there is no default:

options.fetch(:repeat).times{...}

You get a nice error message too:

key not found: :repeat

When the value can be `nil` or `false` and the default is something else:

if (doit = options.fetch(:repeat, 1))
  doit.times{...}
else
  # options[:repeat] is set to nil or false, do something else maybe
end

When you don't want to use the `default`/`default_proc` of a hash:

options = Hash.new(42)
options[:foo] || :default # => 42
options.fetch(:foo, :default) # => :default

Problem

I am not sure in what situation I would want to use `Hash#fetch` over `Hash#[]`. Is there a common scenario in where it would be of good use?

Original source