Skip to content

Instantly share code, notes, and snippets.

@msimonborg
Created August 15, 2017 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msimonborg/6948da391afa08ed840a1522c4a3fc1b to your computer and use it in GitHub Desktop.
Save msimonborg/6948da391afa08ed840a1522c4a3fc1b to your computer and use it in GitHub Desktop.
re-implementation of ActiveSupport's `Hash#deep_merge`
# frozen_string_literal: true
# Implemented in terms of Ruby's built-in ability to pass a block to handle duplicate keys in +merge+
class Hash
def deep_merge(other_hash, &block)
dup.deep_merge!(other_hash, &block)
end
def deep_merge!(other, &block)
merge!(other) do |_key, old_val, new_val|
if old_val.is_a?(Hash) && new_val.is_a?(Hash)
old_val.dup.deep_merge!(new_val, &block)
elsif block_given?
block.call(_key, old_val, new_val)
else
new_val
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment