EdvardM
10/11/2013 - 11:41 AM

combine list of hashes

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