Last active
December 25, 2015 06:39
-
-
Save edvardm/6933336 to your computer and use it in GitHub Desktop.
combine list of hashes
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
# merge_by_common_key(:k, [ { k: 1, a: 2 }, { k: 1, b: 3 }, { k: 2, c: 4} ]) | |
# => [ { k: 1, a: 2, b: 3}, { k: 2, c: 4 } ] | |
def merge_by_common_key(key, list_of_hashes) | |
list_of_hashes.group_by { |h| h[key] }.map { |_, hs| fold_merge(hs) } | |
end | |
def fold_merge(hs) | |
hs.each_with_object({}) { |h, acc| acc.merge!(h) } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment