From: "zverok (Victor Shepelev)" Date: 2022-05-11T18:12:45+00:00 Subject: [ruby-core:108512] [Ruby master Feature#14602] Version of dig that raises error if a key is not present Issue #14602 has been updated by zverok (Victor Shepelev). Just a bit of "design space" analysis: 1. I think `dig!` is unusual for core Ruby. A lot of Rubyists are used that in Rails pairs like `find_by`/`find_by!` are raising/non-raising, but I don't remember any Ruby core API using this convention 2. I don't believe the keyword argument is expressive enough. The "visual structure" of the `dig` signature includes multiple values of user data (and the list of values might be of arbitrary length), so the option at the end of arguments is a) not visible enough and b) not immediately intuitively obvious if it isn't part of user's data 3. In Hash, we already have at least two examples of using `fetch` in a sense "get the value or fail": `#[]` vs `#fetch` and `#values_at` vs `#fetch_values`. It seems like it gives enough precedent to look at the "fetch"-based naming, and it seems like `fetch_dig`, while grammatically not ideal, would be guessable enough, based on existing experience. ---------------------------------------- Feature #14602: Version of dig that raises error if a key is not present https://bugs.ruby-lang.org/issues/14602#change-97554 * 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: