[ruby-core:123212] [Ruby Feature#12282] Hash#dig! for repeated applications of Hash#fetch
From:
"briankung (Brian Kung) via ruby-core" <ruby-core@...>
Date:
2025-09-11 03:02:19 UTC
List:
ruby-core #123212
Issue #12282 has been updated by briankung (Brian Kung).
How about `dig_cons()`, similar to `each_cons()`? They'd be different in that the argument to `each_cons` is how large each output slice is, whereas the arguments to `dig_cons` would represent consecutive keys in a "path" (not the file path, of course). The similarity would be the idea of "consecutive" elements. The "consecutive" in `dig_cons()` would just refer to its inputs rather than its outputs.
----------------------------------------
Feature #12282: Hash#dig! for repeated applications of Hash#fetch
https://bugs.ruby-lang.org/issues/12282#change-114542
* Author: robb (Robb Shecter)
* Status: Open
----------------------------------------
A new feature for your consideration: #dig! which is to #fetch as #dig is to #[]. For me and maybe many others, Hash#fetch is used much more than Hash#[]. And traversing multiple fetches isn't very convenient nor Ruby-like, e.g.: places.fetch(:countries).fetch(:canada).fetch(ontario).
Here's how it would work:
~~~ruby
places = { countries: { canada: true } }
places.dig :countries, :canada # => true
places.dig! :countries, :canada # => true
places.dig :countries, :canada, :ontario # => nil
places.dig! :countries, :canada, :ontario # => KeyError: Key not found: :ontario
~~~
Here's an implementation and tests: https://gist.github.com/dogweather/819ccdb41c9db0514c163cfdb1c528e2
--
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/lists/ruby-core.ml.ruby-lang.org/