Ruby将具有相同键和多个值的哈希数组合在一起

时间:2017-09-21 19:37:07

标签: arrays ruby hash

我有以下数组实际上是两个数组的组合。我的目标是使用employeeId为898989的2个哈希值可以组合在一起,我可以将它们的计数加在一起并将它们的类型更改为两者。我尝试了下面的代码,它接近我想要的,但是我失去了哈希的其他值。是否有任何简单的方法来映射所有值并进行操作,如添加我想要的计数?

combined = [{"@rid"=>"#-2:1", "employeeId"=>   "898989", "count"=>1, :type=>"wiki"  },
       {"@rid"=>"#-2:3", "employeeId"=>  "2423213", "count"=>7, :type=>"search"},
       {"@rid"=>"#-2:2", "employeeId"=>   "555555", "count"=>2, :type=>"search"},
       {"@rid"=>"#-2:5", "employeeId"=>   "898989", "count"=>2, :type=>"search"},
       {"@rid"=>"#-2:1", "employeeId"=>  "5453454", "count"=>1, :type=>"search"},
       {"@rid"=>"#-2:4", "employeeId"=>"987654321", "count"=>1, :type=>"search"}]

merged_array_hash = combined.group_by { |h1| h1["employeeId"] }.map do |k,v|
    { "employeeId" => k, :types =>  v.map { |h2| h2[:type] }.join(", ") }
end

merged_array_hash最终成为:

[{employeeId: "898989",types: "wiki, search"},
{employeeId: "2423213",types: "search"},
{employeeId: "555555",types: "search"},
{employeeId: "5453454",types:"search"},
{employeeId: "987654321",types: "search"}]

我想要得到的东西:

[{employeeId: "898989",type: "both", count: 2},
{employeeId: "2423213",type: "search", count: 7},
{employeeId: "555555",type: "search", count: 2},
{employeeId: "5453454",type:"search", count: 1},
{employeeId: "987654321",type: "search", count: 1}]

2 个答案:

答案 0 :(得分:0)

不漂亮,但它会完成工作:

combined.group_by { |h1| h1["employeeId"] }.map do |k,v|
  types = v.map { |h2| h2[:type] }  
  count = v.sum { |x| x['count'] } 

  { employeeId: k, 
    types: (types.length == 1 ? types[0] : 'both'), 
    count: count }  

end  

=> [{:employeeId =>"898989", :types=>"both", :count=>3},
    {:employeeId =>"2423213", :types=>"search", :count=>7},
    {:employeeId =>"555555", :types=>"search", :count=>2},
    {:employeeId =>"5453454", :types=>"search", :count=>1},
    {:employeeId =>"987654321", :types=>"search", :count=>1}]

答案 1 :(得分:0)

也不漂亮,也会完成工作,可能更具可读性

hash = {}
combined.each do |h|
  employeeId, count, type = h.values_at("employeeId", "count", :type)
  if hash.include? employeeId
    hash[employeeId][:count] += count
    hash[employeeId][:type] = "both"  #assumes duplicates can only occur if item is in both lists
  else
    hash[employeeId] = { :employeeId => employeeId, :type => type, :count => count }
  end
end
hash.values

测试:

[{:employeeId=>"898989", :type=>"both", :count=>3},
{:employeeId=>"2423213", :type=>"search", :count=>7},
{:employeeId=>"555555", :type=>"search", :count=>2},
{:employeeId=>"5453454", :type=>"search", :count=>1},
{:employeeId=>"987654321", :type=>"search", :count=>1}]