[ruby-core:115300] [Ruby master Feature#14602] Version of dig that raises error if a key is not present

Issue #14602 has been updated by mame (Yusuke Endoh). We discussed at the dev meeting but did not reach a conclusion. But there has been some progress. * @akr said we shouldn't add new vocabulary, and Matz agreed. * There is `Array#fetch` which throws an exception when it is not found, so we want to use this vocabulary: `fetch_*` or `*_fetch` * Matz didn't like any of the proposed `fetch_each` `fetch_all` `fetch_tail` `fetch_end` * Matz prefers `dig` or `recursive` to `deep` to represent this behavior. * `deep` sounds to be an operation on the entire data structure, due to the influence of deep_copy. * Matz was interested in how `dig_fetch` or `fetch_dig` would sound to English native speakers. * Matz also mentioned `recursive_fetch`, but said it seemed a bit long. ---------------------------------------- Feature #14602: Version of dig that raises error if a key is not present https://bugs.ruby-lang.org/issues/14602#change-105218 * 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/
participants (1)
-
mame (Yusuke Endoh)