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?
For rails 3.0.0+ or higher version there is the deep_merge function for ActiveSupport that does exactly what you ask for.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With