# How to update nested Hashes?

**URL:** <https://www.ruby-forum.com/t/how-to-update-nested-hashes/64794>\
**Category:** Ruby\
**Created:** [August 15, 2006, 2:19pm UTC](https://www.ruby-forum.com/t/how-to-update-nested-hashes/64794 "2006-08-15T14:19:03Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Hammed\_M](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/7feea3/32.png) [@Hammed\_M](https://www.ruby-forum.com/u/Hammed_M)\
**Post date:** [August 15, 2006, 2:19pm UTC](https://www.ruby-forum.com/t/how-to-update-nested-hashes/64794/1 "2006-08-15T14:19:03Z")

</div>

Given two nested Hashes, is there an easy way to update one with the  
other?

a = {:top =\> {:foo =\> {:a =\> 1}, :bar =\> {:b =\> 2}}}  
b = {:top =\> {:bar =\> {:c =\> 3}}}

what I’d like is

a.nested\_update(b) =\> {:top =\> {:foo =\> {:a =\> 1}, :bar =\> {:c =\> 3}}}

Thanks

Hammed

---

<div class="post-metadata">

**Author:** ![Hammed\_M](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/7feea3/32.png) [@Hammed\_M](https://www.ruby-forum.com/u/Hammed_M)\
**Post date:** [August 15, 2006, 2:19pm UTC](https://www.ruby-forum.com/t/how-to-update-nested-hashes/64794/2 "2006-08-15T14:19:04Z")

</div>

Hi –

On Mon, 14 Aug 2006, Hammed M. wrote:

> Given two nested Hashes, is there an easy way to update one with the other?
> 
> a = {:top =\> {:foo =\> {:a =\> 1}, :bar =\> {:b =\> 2}}}  
> b = {:top =\> {:bar =\> {:c =\> 3}}}
> 
> what I’d like is
> 
> a.nested\_update(b) =\> {:top =\> {:foo =\> {:a =\> 1}, :bar =\> {:c =\> 3}}}

You could do something like:

def a.nested\_update(b)  
each\_key {|k| self[k].update(b[k])}  
end

David

---

<div class="post-metadata">

**Author:** ![Hammed\_M](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/7feea3/32.png) [@Hammed\_M](https://www.ruby-forum.com/u/Hammed_M)\
**Post date:** [August 15, 2006, 2:19pm UTC](https://www.ruby-forum.com/t/how-to-update-nested-hashes/64794/3 "2006-08-15T14:19:06Z")

</div>

Thanks David!
