Created
August 15, 2017 20:47
-
-
Save msimonborg/6948da391afa08ed840a1522c4a3fc1b to your computer and use it in GitHub Desktop.
re-implementation of ActiveSupport's `Hash#deep_merge`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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