Combining multidimensional hashes in Ruby

I have two hashes that have a structure similar to this:

hash_a = { :a => { :b => { :c => "d" } } }
hash_b = { :a => { :b => { :x => "y" } } }

I want to combine them together to create the following hash:

{ :a => { :b => { :c => "d", :x => "y" } } }

The merge function will replace the value: a in the first hash with the value: a in the second hash. So, I wrote my own recursive merge function, which looks like this:

def recursive_merge( merge_from, merge_to )
    merged_hash = merge_to
    first_key = merge_from.keys[0]
    if merge_to.has_key?(first_key)
        merged_hash[first_key] = recursive_merge( merge_from[first_key], merge_to[first_key] )
    else
        merged_hash[first_key] = merge_from[first_key]
    end
    merged_hash
end

But I get a runtime error: can't add a new key into hash during iteration. What is the best way to combine these hashes in Ruby?

+5
source share
6 answers

If you change the first row of recursive_merge to

merged_hash = merge_to.clone

works as expected:

recursive_merge(hash_a, hash_b)    
->    {:a=>{:b=>{:c=>"d", :x=>"y"}}}

Changing a hash when moving it is difficult; you need a β€œworkspace” to accumulate your results.

+6

Ruby existing Hash#merge , . "" ; .

hash_a = { :a => { :b => { :c => "d", :z => 'foo' } } }
hash_b = { :a => { :b => { :x => "y", :z => 'bar' } } }

def recurse_merge(a,b)
  a.merge(b) do |_,x,y|
    (x.is_a?(Hash) && y.is_a?(Hash)) ? recurse_merge(x,y) : [*x,*y]
  end
end

p recurse_merge( hash_a, hash_b )
#=> {:a=>{:b=>{:c=>"d", :z=>["foo", "bar"], :x=>"y"}}}

, :

class Hash
  def merge_recursive(o)
    merge(o) do |_,x,y|
      if x.respond_to?(:merge_recursive) && y.is_a?(Hash)
        x.merge_recursive(y)
      else
        [*x,*y]
      end
    end
  end
end

p hash_a.merge_recursive hash_b
#=> {:a=>{:b=>{:c=>"d", :z=>["foo", "bar"], :x=>"y"}}}
+9

:

merged_hash = hash_a.merge(hash_b){|k,hha,hhb| hha.merge(hhb){|l,hhha,hhhb| hhha.merge(hhhb)}}

imediatly merge hash_a, merge merge!

3 4, :

merged_hash = hash_a.deep_merge(hash_b)

hash_a.deep_merge!(hash_b)
+7

:

class Hash
  def recursive_merge(hash = nil)
    return self unless hash.is_a?(Hash)
    base = self
    hash.each do |key, v|
      if base[key].is_a?(Hash) && hash[key].is_a?(Hash)
        base[key].recursive_merge(hash[key])
      else
        base[key]= hash[key]
      end
    end
    base
  end
end
+2

, @Phrogz

def recurse_merge( merge_from, merge_to )
  merge_from.merge(merge_to) do |_,x,y|
    (x.is_a?(Hash) && y.is_a?(Hash)) ? recurse_merge(x,y) : x
  end
end

, merge_from hash

0

, bang , 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

using HashRecursive Hash::merge Hash::merge!, . , .

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


An example to answer the question. It is very simple:

hash_a  =   { :a => { :b => { :c => "d" } } }
hash_b  =   { :a => { :b => { :x => "y" } } }

puts hash_a.merge(hash_b)                                   # Won't override hash_a
# output:   { :a => { :b => { :x => "y" } } }

puts hash_a                                                 # hash_a is unchanged
# output:   { :a => { :b => { :c => "d" } } }

hash_a.merge!(hash_b, recursive=true)                       # Will override hash_a

puts hash_a                                                 # hash_a was changed
# output:   { :a => { :b => { :c => "d", :x => "y" } } }

For an advanced example, consider this answer .

Also take a look at my recursive version Hash::each( Hash::each_pair) here .

0
source

All Articles