Project

General

Profile

Actions

Feature #12282

open

Hash#dig! for repeated applications of Hash#fetch

Added by robb (Robb Shecter) over 5 years ago. Updated almost 3 years ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:74946]

Description

A new feature for your consideration: #dig! which is to #fetch as #dig is to #[]. For me and maybe many others, Hash#fetch is used much more than Hash#[]. And traversing multiple fetches isn't very convenient nor Ruby-like, e.g.: places.fetch(:countries).fetch(:canada).fetch(ontario).

Here's how it would work:

places = { countries: { canada: true } }

places.dig  :countries, :canada  # => true
places.dig! :countries, :canada  # => true

places.dig  :countries, :canada, :ontario  # => nil
places.dig! :countries, :canada, :ontario  # => KeyError: Key not found: :ontario

Here's an implementation and tests: https://gist.github.com/dogweather/819ccdb41c9db0514c163cfdb1c528e2


Related issues

Has duplicate Ruby master - Feature #15563: #dig that throws an exception if a key doesn't existOpenActions
Has duplicate Ruby master - Feature #14602: Version of dig that raises error if a key is not presentOpenActions
Actions

Also available in: Atom PDF