Skip to content

Instantly share code, notes, and snippets.

@marian13
Last active April 17, 2022 11:55
Show Gist options
  • Save marian13/22744b83fac3a9a4276b74a3f5182916 to your computer and use it in GitHub Desktop.
Save marian13/22744b83fac3a9a4276b74a3f5182916 to your computer and use it in GitHub Desktop.

Deep Merge Concat

Can be useful for "inheritance" in YAML.

require "active_support"
require "active_support/core_ext/hash/deep_merge"
class Hash
def deep_merge_concat(other, &block)
self.deep_merge(other) do |key, this_val, other_val|
other_val = this_val + other_val if (this_val.is_a?(::Array) && other_val.is_a?(::Array))
block ? block.call(key, this_val, other_val) : other_val
end
end
end
h1 = {a:{b: [1, 2, 3], c: {d: 1}}}
h2 = {a:{b: [4, 5, 6], c: {d: 2}}}
h1.deep_merge_concat(h2)
# => {:a=>{:b=>[1, 2, 3, 4, 5, 6], :c=>{:d=>2}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment