Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: merge nested hash

I would like to merge a nested hash.

a = {:book=>     [{:title=>"Hamlet",       :author=>"William Shakespeare"       }]}  b = {:book=>     [{:title=>"Pride and Prejudice",       :author=>"Jane Austen"       }]} 

I would like the merge to be:

{:book=>    [{:title=>"Hamlet",       :author=>"William Shakespeare"},     {:title=>"Pride and Prejudice",       :author=>"Jane Austen"}]} 

What is the nest way to accomplish this?

like image 562
user1223862 Avatar asked Feb 21 '12 16:02

user1223862


2 Answers

For rails 3.0.0+ or higher version there is the deep_merge function for ActiveSupport that does exactly what you ask for.

like image 171
xlembouras Avatar answered Sep 22 '22 10:09

xlembouras


I found a more generic deep-merge algorithm here, and used it like so:

class ::Hash     def deep_merge(second)         merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }         self.merge(second, &merger)     end end  a.deep_merge(b) 
like image 28
Jon M Avatar answered Sep 23 '22 10:09

Jon M