From: "amcaplan (Ariel Caplan)" Date: 2022-05-24T22:02:51+00:00 Subject: [ruby-core:108682] [Ruby master Feature#14602] Version of dig that raises error if a key is not present Issue #14602 has been updated by amcaplan (Ariel Caplan). We can think of this as either a variation of `fetch` or a variation of `dig`. Ultimately it's both, of course, just depends how you look at it. If we think of it as `fetch`-based, `deep_fetch` would be OK but we also might go with something that really describes quite literally what it does, which is `fetch` recursively. So, `fetch_recursive` or `rfetch` (think of `Array#bsearch` as prior art - though of course it's not 100% comparable) might be the way to go. If we take the `dig`-based perspective, it's `dig` but non-permissive. So `dig_strict` might be the most literal way of explaining what it does. Rather than advocating strongly for 1 specific word, I'd just gently recommend that we avoid introducing more dig-like verbs. While seasoned Rubyists will know the difference, newcomers won't have any obvious reason to assume that `dig` differs from `traverse` in strictness. At least there's a convention for `fetch` vs `[]` which already exists and we can use it to avoid introducing more new language/concepts. ---------------------------------------- Feature #14602: Version of dig that raises error if a key is not present https://bugs.ruby-lang.org/issues/14602#change-97723 * 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/ Unsubscribe: