Issue #12282 has been updated by robb (Robb Shecter).


Thanks everyone, for the discussion. I realize that my original comparison with #dig had a typographical error. Here's a gem implementation, with examples that are correct: https://github.com/dogweather/digbang

```
require 'dig_bang'

places = {
  world: {
    uk: true,
    usa: true
  }
}

# No difference when the key exists
places.dig  :world, :uk # true
places.dig! :world, :uk # true

# A relevant error when the key is missing
places.dig  :world, :uk, :alaska # nil
places.dig! :world, :uk, :alaska # KeyError: Key not found: :alaska
```

About the method name with the bang. I see that this might be more of a Rails naming convention, which `!` methods perform the same action, but throw an error instead of returning a `nil` on failure. And that's exactly my intent with `dig!` vs. `dig`. Basically, a "checked" dig. I don't think that Ruby has a naming convention for an alternate interface which throws an exception vs. return a nil. (?)

```
module DigBang
  def self.fetch_all(fetchable, keys)
    keys.reduce(fetchable) { |a, e| a.fetch(e) }
  end
end

class Hash
  def dig!(*keys)
    DigBang.fetch_all(self, keys)
  end
end

class Array
  def dig!(*keys)
    DigBang.fetch_all(self, keys)
  end
end
```

----------------------------------------
Feature #12282: Hash#dig! for repeated applications of Hash#fetch
https://bugs.ruby-lang.org/issues/12282#change-75939

* Author: robb (Robb Shecter)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
----------------------------------------
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/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>