Ruby: merge nested hash

前端 未结 9 1863
渐次进展
渐次进展 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 07:07

    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

提交回复
热议问题