Skip to content

Instantly share code, notes, and snippets.

@edvardm
Last active December 25, 2015 06:39
Show Gist options
  • Save edvardm/6933336 to your computer and use it in GitHub Desktop.
Save edvardm/6933336 to your computer and use it in GitHub Desktop.
combine list of hashes
# 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