Ruby: merge nested hash

RubyHashMergeNested

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

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

Solution 2 - Ruby

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)

Solution 3 - Ruby

To add on to Jon M and koendc's answers, the below code will handle merges of hashes, and :nil as above, but it will also union any arrays that are present in both hashes (with the same key):

class ::Hash
  def deep_merge(second)
    merger = proc { |_, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : Array === v1 && Array === v2 ? v1 | v2 : [:undefined, nil, :nil].include?(v2) ? v1 : v2 }
    merge(second.to_h, &merger)
  end
end


a.deep_merge(b)

Solution 4 - Ruby

For variety's sake - and this will only work if you want to merge all the keys in your hash in the same way - you could do this:

a.merge(b) { |k, x, y| x + y }

When you pass a block to Hash#merge, k is the key being merged, where the key exists in both a and b, x is the value of a[k] and y is the value of b[k]. The result of the block becomes the value in the merged hash for key k.

I think in your specific case though, nkm's answer is better.

Solution 5 - Ruby

A little late to answer your question, but I wrote a fairly rich deep merge utility awhile back that is now maintained by Daniel Deleo on Github: https://github.com/danielsdeleo/deep_merge

It will merge your arrays exactly as you want. From the first example in the docs:

So if you have two hashes like this:

   source = {:x => [1,2,3], :y => 2}
   dest =   {:x => [4,5,'6'], :y => [7,8,9]}
   dest.deep_merge!(source)
   Results: {:x => [1,2,3,4,5,'6'], :y => 2}

It won't merge :y (because int and array aren't considered mergeable) - using the bang (!) syntax causes the source to overwrite.. Using the non-bang method will leave dest's internal values alone when an unmergeable entity is found. It will add the arrays contained in :x together because it knows how to merge arrays. It handles arbitrarily deep merging of hashes containing whatever data structures.

Lots more docs on Daniel's github repo now..

Solution 6 - Ruby

All answers look to me overcomplicated. Here's what I came up with eventually:

# @param tgt [Hash] target hash that we will be **altering**
# @param src [Hash] read from this source hash
# @return the modified target hash
# @note this one does not merge Arrays
def self.deep_merge!(tgt_hash, src_hash)
  tgt_hash.merge!(src_hash) { |key, oldval, newval|
    if oldval.kind_of?(Hash) && newval.kind_of?(Hash)
      deep_merge!(oldval, newval)
    else
      newval
    end
  }
end

P.S. use as public, WTFPL or whatever license

Solution 7 - Ruby

Here is even better solution for recursive merging that uses refinements and has bang method alongside with block support. This code does work on pure Ruby.

module HashRecursive
	refine Hash do
		def merge(other_hash, recursive=false, &block)
			if recursive
				block_actual = Proc.new {|key, oldval, newval|
					newval = block.call(key, oldval, newval) if block_given?
					[oldval, newval].all? {|v| v.is_a?(Hash)} ? oldval.merge(newval, &block_actual) : newval
				}	
				self.merge(other_hash, &block_actual)
			else
				super(other_hash, &block)
			end
		end
		def merge!(other_hash, recursive=false, &block)
			if recursive
				self.replace(self.merge(other_hash, recursive, &block))
			else
				super(other_hash, &block)
			end
		end
	end
end

using HashRecursive

After using HashRecursive was executed you can use default Hash::merge and Hash::merge! as if they haven't been modified. You can use blocks with these methods as before.

The new thing is that you can pass boolean recursive (second argument) to these modified methods and they will merge hashes recursively.


Example for simple usage is written at [this answer](https://stackoverflow.com/a/49139981/8410844 "@MOPO3OB's answer"). Here is an advanced example.

The example in this question is bad because it got nothing to do with recursive merging. Following line would meet question's example:

a.merge!(b) {|k,v1,v2| [v1, v2].all? {|v| v.is_a?(Array)} ? v1+v2 : v2}

Let me give you a better example to show the power of the code above. Imagine two rooms, each have one bookshelf in it. There are 3 rows on each bookshelf and each bookshelf currently have 2 books. Code:

room1	=	{
	:shelf	=>	{
		:row1	=>	[
			{
				:title	=>	"Hamlet",
				:author	=>	"William Shakespeare"
			}
		],
		:row2	=>	[
			{
				:title	=>	"Pride and Prejudice",
				:author	=>	"Jane Austen"
			}
		]
	}
}

room2	=	{
	:shelf	=>	{
		:row2	=>	[
			{
				:title	=>	"The Great Gatsby",
				:author	=>	"F. Scott Fitzgerald"
			}
		],
		:row3	=>	[
			{
				:title	=>	"Catastrophe Theory",
				:author	=>	"V. I. Arnol'd"
			}
		]
	}
}

We are going to move books from the shelf in the second room to the same rows on the shelf in the first room. First we will do this without setting recursive flag, i.e. same as using unmodified Hash::merge!:

room1.merge!(room2) {|k,v1,v2| [v1, v2].all? {|v| v.is_a?(Array)} ? v1+v2 : v2}
puts room1

The output will tell us that the shelf in the first room would look like this:

room1	=	{
	:shelf	=>	{
		:row2	=>	[
			{
				:title	=>	"The Great Gatsby",
				:author	=>	"F. Scott Fitzgerald"
			}
		],
		:row3	=>	[
			{
				:title	=>	"Catastrophe Theory",
				:author	=>	"V. I. Arnol'd"
			}
		]
	}
}

As you can see, not having recursive forced us to throw out our precious books.

Now we will do the same thing but with setting recursive flag to true. You can pass as second argument either recursive=true or just true:

room1.merge!(room2, true) {|k,v1,v2| [v1, v2].all? {|v| v.is_a?(Array)} ? v1+v2 : v2}
puts room1

Now the output will tell us that we actually moved our books:

room1	=	{
	:shelf	=>	{
		:row1	=>	[
			{
				:title	=>	"Hamlet",
				:author	=>	"William Shakespeare"
			}
		],
		:row2	=>	[
			{
				:title	=>	"Pride and Prejudice",
				:author	=>	"Jane Austen"
			},
			{
				:title	=>	"The Great Gatsby",
				:author	=>	"F. Scott Fitzgerald"
			}
		],
		:row3	=>	[
			{
				:title	=>	"Catastrophe Theory",
				:author	=>	"V. I. Arnol'd"
			}
		]
	}
}

That last execution could be rewritten as following:

room1 = room1.merge(room2, recursive=true) do |k, v1, v2|
	if v1.is_a?(Array) && v2.is_a?(Array)
		v1+v2
	else
		v2
	end
end
puts room1

or

block = Proc.new {|k,v1,v2| [v1, v2].all? {|v| v.is_a?(Array)} ? v1+v2 : v2}
room1.merge!(room2, recursive=true, &block)
puts room1

That's it. Also take a look at my recursive version of Hash::each(Hash::each_pair) [here](https://stackoverflow.com/a/49167243/8410844 "@MOPO3OB's answer").

Solution 8 - Ruby

I think Jon M's answer is the best, but it fails when you merge in a hash with a nil/undefined value. This update solves the issue:

class ::Hash
    def deep_merge(second)
        merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : [:undefined, nil, :nil].include?(v2) ? v1 : v2 }
        self.merge(second, &merger)
    end
end

a.deep_merge(b)

Solution 9 - Ruby

a[:book] = a[:book] + b[:book]

Or

a[:book] <<  b[:book].first

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1223862View Question on Stackoverflow
Solution 1 - RubyxlembourasView Answer on Stackoverflow
Solution 2 - RubyJon MView Answer on Stackoverflow
Solution 3 - RubyDanView Answer on Stackoverflow
Solution 4 - RubyRussellView Answer on Stackoverflow
Solution 5 - RubySteve MidgleyView Answer on Stackoverflow
Solution 6 - RubyakostadinovView Answer on Stackoverflow
Solution 7 - RubyMOPO3OBView Answer on Stackoverflow
Solution 8 - RubykoendcView Answer on Stackoverflow
Solution 9 - RubynkmView Answer on Stackoverflow