# Addition of 'deep\_assoc\` method to Hash in core\_ext

**URL:** <https://discuss.rubyonrails.org/t/addition-of-deep-assoc-method-to-hash-in-core-ext/70524>\
**Category:** rubyonrails-core\
**Created:** [April 16, 2015, 11:02pm UTC](https://discuss.rubyonrails.org/t/addition-of-deep-assoc-method-to-hash-in-core-ext/70524 "2015-04-16T23:02:48Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![micahbuckleyfarlee](https://avatars.discourse-cdn.com/v4/letter/m/dc4da7/32.png) [@micahbuckleyfarlee](https://discuss.rubyonrails.org/u/micahbuckleyfarlee)\
**Post date:** [April 16, 2015, 11:02pm UTC](https://discuss.rubyonrails.org/t/addition-of-deep-assoc-method-to-hash-in-core-ext/70524/1 "2015-04-16T23:02:48Z")

</div>

Hello,

I wanted to see what people thought about adding a “deep\_assoc” method to Hash in core\_ext.

Given a hash like this:

hash = {a: {b: {c: :d}}}

Its usage would look like this:

hash.deep\_assoc(:a, :b, :c)

# =\> :d

hash.deep\_assoc(:a, :e, :f)

# =\> nil

It is basically a much cleaner way to avoid this pattern:

hash.try(:, :a).try(:, :b).try(:, :c)

It is the one thing which I find myself continually missing in Hash.

A basic implementation looks like this:

class Hash

def deep\_assoc(\*keys)

current = keys.shift

return self[current] if keys.empty?

return nil unless self[current].is\_a?(Hash)

self[current].deep\_assoc(keys)

end

end

Please let me know your thoughts.

Thanks!

Micah Buckley-Farlee

---

<div class="post-metadata">

**Author:** ![Mike\_Ragalie](https://avatars.discourse-cdn.com/v4/letter/m/b5ac83/32.png) [@Mike\_Ragalie](https://discuss.rubyonrails.org/u/Mike_Ragalie)\
**Post date:** [April 16, 2015, 11:55pm UTC](https://discuss.rubyonrails.org/t/addition-of-deep-assoc-method-to-hash-in-core-ext/70524/2 "2015-04-16T23:55:43Z")

</div>

I would use this often. It seems more like `#fetch` than `#assoc` though; would it be better to name it `#deep_fetch` and have it follow the same conventions re: `KeyError` or default value?

-Mike

---

<div class="post-metadata">

**Author:** ![rafaelfranca](https://sea2.discourse-cdn.com/rubyonrails/user_avatar/discuss.rubyonrails.org/rafaelfranca/32/616_2.png) [@rafaelfranca](https://discuss.rubyonrails.org/u/rafaelfranca)\
**Post date:** [April 17, 2015, 12:01am UTC](https://discuss.rubyonrails.org/t/addition-of-deep-assoc-method-to-hash-in-core-ext/70524/3 "2015-04-17T00:01:26Z")

</div>

I think we had this same request several times and we always rejected it.

I never had to use this pattern and I believe it may be a code smell, but I’m not sure about your usage, so it would be great if you explain why you have this pattern in your application and how often.

The reason that I’m asking that we are in a kind of “code freeze” of Active Support core extension and we avoid the maximum to add new stuff there unless it is really well justified common pattern or it will be used by the framework itself.

I also recommend you to propose to Ruby itself, if we could get it accepted in the language itself we can backport the feature inside Rails.

This is the process that we are even using for methods proposed by Core team members. David proposed Object#itself and we also implemented it inside Ruby 2.2. That way we were able to remove the Rails implementation after we required only Ruby 2.2+.

---

<div class="post-metadata">

**Author:** ![Mike\_Ragalie](https://avatars.discourse-cdn.com/v4/letter/m/b5ac83/32.png) [@Mike\_Ragalie](https://discuss.rubyonrails.org/u/Mike_Ragalie)\
**Post date:** [April 17, 2015, 12:11am UTC](https://discuss.rubyonrails.org/t/addition-of-deep-assoc-method-to-hash-in-core-ext/70524/4 "2015-04-17T00:11:44Z")

</div>

It comes up frequently if you’re consuming XML. It’s not uncommon to receive something like this in the happy case:

Value

And something like this in the unhappy case:

No foos

It’s cleaner to do something like:

```ruby

errors = Array.wrap(xml.deep_fetch(["FooResponse", "Errors", "Error"], []))

```

than

```ruby

errors = Array.wrap(xml.try(:[], "FooResponse").try(:[], "Errors").try(:[], "Error"))

-Mike
```

---

<div class="post-metadata">

**Author:** ![micahbuckleyfarlee](https://avatars.discourse-cdn.com/v4/letter/m/dc4da7/32.png) [@micahbuckleyfarlee](https://discuss.rubyonrails.org/u/micahbuckleyfarlee)\
**Post date:** [April 17, 2015, 12:36am UTC](https://discuss.rubyonrails.org/t/addition-of-deep-assoc-method-to-hash-in-core-ext/70524/5 "2015-04-17T00:36:37Z")

</div>

Thank you for the feedback!

I think the most common use case for me is consuming external APIs, in which case it presents itself fairly often. (It seems particularly endemic to XML APIs.)

There, it is often the case that you need to retrieve a deeply nested value, but cannot rely on its presence.

It was also inspired by clojure’s assoc-in [1], which does the same thing and which I now miss in Ruby.

I certainly understand the extreme reticence to add anything to core extension, but I thought the simplicity and potentially high utility here would perhaps justify it.

Thanks for the suggestion to propose it to Ruby as well, I will do that.

[1] [assoc-in - clojure.core | ClojureDocs - Community-Powered Clojure Documentation and Examples](https://clojuredocs.org/clojure.core/assoc-in)

---

<div class="post-metadata">

**Author:** ![Yuki\_Nishijima](https://avatars.discourse-cdn.com/v4/letter/y/e5b9ba/32.png) [@Yuki\_Nishijima](https://discuss.rubyonrails.org/u/Yuki_Nishijima)\
**Post date:** [April 17, 2015, 12:28pm UTC](https://discuss.rubyonrails.org/t/addition-of-deep-assoc-method-to-hash-in-core-ext/70524/6 "2015-04-17T12:28:05Z")

</div>

-1 on this.

As you mentioned earlier, I’ve seen this pattern so often when parsing XML data, and replaced every single usecase with one of the followings:

- [SAX parser](http://en.wikipedia.org/wiki/Simple_API_for_XML)

- [xpath](http://en.wikipedia.org/wiki/XPath)

In general, hash creation from a XML file using a DOM tree is quite slow and quickly becomes a performance bottleneck. It’s recommended to write a SAX parser when it has be fast. When performance is not a big problem(e.g. testing), consider using xpath. Then the code that reads the xml value above:

> xml = response.body

> xml = convert\_xml\_to\_path(xml)

> errors = Array.wrap(xml.try(:, “FooResponse”).try(:, “Errors”).try(:, “Error”))

will become:

> xml = response.body

> dom = Nokogiri::XML(xml)

> dom.xpath(“FooResponse/Errors/Error”)

Which looks cleaner than the original proposal here. To me, it seems like deep\_assoc is trying to solve a problem that is already solved.

I’ve never seen this pattern except when parsing XML and this pattern shouldn’t be used.

---

<div class="post-metadata">

**Author:** ![sikachu](https://sea2.discourse-cdn.com/rubyonrails/user_avatar/discuss.rubyonrails.org/sikachu/32/628_2.png) [@sikachu](https://discuss.rubyonrails.org/u/sikachu)\
**Post date:** [April 17, 2015, 1:23pm UTC](https://discuss.rubyonrails.org/t/addition-of-deep-assoc-method-to-hash-in-core-ext/70524/7 "2015-04-17T13:23:22Z")

</div>

I’m -1 on adding this as well. I agree with Yuki that for XML traversing it’s better to use something like Nokogiri.

For other use case that you have to go deep down the chain, I think you’d better off creating a class that represent that data structure and maybe use a null object pattern for those methods that could return nil, but still wanted to be chainable.

-Prem
