合并哈希嵌套在数组中,同时仅使用不同的键

时间:2014-03-23 15:25:31

标签: ruby arrays merge hashmap

我有一个巨大的阵列(40.000+元素)名称,具有以下结构:

names = [
  {"Aabjørn"=>{:gender=>"male", :nationality=>"danish"}},
  {"Aagot"=>{:gender=>"female", :nationality=>"swedish"}},
  {"Aagot"=>{:gender=>"female", :nationality=>"norwegian"}},
  {"Aagot"=>{:gender=>"female", :nationality=>"danish"}},
  {"Aake"=>{:gender=>"male", :nationality=>"finnish"}},
  {"Aake"=>{:gender=>"female", :nationality=>"finnish"}}]

我的目标是在合并嵌套数据时只保留一个键(实际名称),这样数组就像这样:

new_names_array = [
  {"Aabjørn"=>{:gender=>"male", :nationality=>"danish"}},
  {"Aagot"=>{:gender=>"female", :nationality=>["swedish", "norwegian", "danish"]}},
  {"Aake"=>{:gender=>["male", "female"], :nationality=>"finnish"}},
]

如何迭代这个数组并以这种方式合并它的值?

1 个答案:

答案 0 :(得分:1)

我会这样做:

merge_ary = names.group_by { |h| h.keys.first }.map do |k,v|
  { k => v.inject({:gender => '', :nationality => ''}) do |new_hash,inner_hash|
    new_hash.merge(inner_hash[k]) do |key,o,n|
      if o == n or o.empty?
        n
      elsif o != n 
        [o,n].flatten.uniq
      end
    end
  end }
end

merge_ary
# => [{"Aabjørn"=>{:gender=>"male", :nationality=>"danish"}},
#     {"Aagot"=>
#       {:gender=>"female", :nationality=>["swedish", "norwegian", "danish"]}},
#     {"Aake"=>{:gender=>["male", "female"], :nationality=>"finnish"}}]