Project

General

Profile

Actions

Feature #14602

open

Version of dig that raises error if a key is not present

Added by amcaplan (Ariel Caplan) almost 7 years ago. Updated 5 months ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:86102]

Description

Currently, if I have a hash like this:

{
    :name => {
        :first => "Ariel",
        :last => "Caplan"
    }
}

and I want to navigate confidently and raise a KeyError if something is missing, I can do:

hash.fetch(:name).fetch(:first)

Unfortunately, the length of the name, combined with the need to repeat the method name every time, means most programmers are more likely to do this:

hash[:name][:first]

which leads to many unexpected errors.

The Hash#dig method made it easy to access methods safely from a nested hash; I'd like to have something similar for access without error protection, and I'd think the most natural name would be Hash#dig!. It would work like this:

hash = {
    :name => {
        :first => "Ariel",
        :last => "Caplan"
    }
}
hash.dig!(:name, :first) # => Ariel
hash.dig!(:name, :middle) # raises KeyError (key not found: :middle)
hash.dig!(:name, :first, :foo) # raises TypeError (String does not have #dig! method)

Related issues 2 (2 open0 closed)

Is duplicate of Ruby master - Feature #12282: Hash#dig! for repeated applications of Hash#fetchOpenActions
Has duplicate Ruby master - Feature #15563: #dig that throws an exception if a key doesn't existOpenActions
Actions

Also available in: Atom PDF

Like1
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like1Like0Like0Like1