Paul
Groves
Ltd

Hash fetch with a default

Passing a default value when using fetch to access a hash can be a great way to avoid key not found errors when looking for optional keys.

An example is when looking for nested attributes in a Rails params hash, such as looking for tasks associated to a project:

params.fetch(:tasks, {})[:id]

By passing an empty hash in as the default, our request for the :id attribute will simply return nil if there are no tasks in the params rather than raise an error.