From: "edmz (Ed Mz) via ruby-core" <ruby-core@...>
Date: 2024-01-05T18:09:55+00:00
Subject: [ruby-core:116035] [Ruby master Feature#14602] Version of dig that raises error if a key is not present

Issue #14602 has been updated by edmz (Ed Mz).


Following what @mame explained about Matz expectations, I would like to (*humbly*) suggest another option:

* `dig_expected`

(and a my +1 to `dig_strict`)

----------------------------------------
Feature #14602: Version of dig that raises error if a key is not present
https://bugs.ruby-lang.org/issues/14602#change-106033

* Author: amcaplan (Ariel Caplan)
* Status: Open
* Priority: Normal
----------------------------------------
Currently, if I have a hash like this:

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

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

~~~ ruby
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:

~~~ ruby
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:

~~~ ruby
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)
~~~




-- 
https://bugs.ruby-lang.org/
 ______________________________________________
 ruby-core mailing list -- ruby-core@ml.ruby-lang.org
 To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org
 ruby-core info -- https://ml.ruby-lang.org/mailman3/postorius/lists/ruby-core.ml.ruby-lang.org/