Ruby: merge nested hash

前端 未结 9 1938
渐次进展
渐次进展 2020-11-30 06:25

I would like to merge a nested hash.

a = {:book=>
    [{:title=>\"Hamlet\",
      :author=>\"William Shakespeare\"
      }]}

b = {:book=>
    [{         


        
9条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 06:55

    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)
    

提交回复
热议问题