Ruby: merge nested hash

user1223862 picture user1223862 · Feb 21, 2012 · Viewed 39.7k times · Source

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?

Answer

xlembouras picture xlembouras · Sep 25, 2012

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