Ruby - 按键分组哈希数组

时间:2014-06-30 18:36:41

标签: ruby arrays hash

我有一系列哈希(已编辑):

data = [
    {id: 1, name: "Amy", win: 1, defeat: 0},
    {id: 1, name: "Amy", win: 1, defeat: 3},
    {id: 2, name: "Carl", win: 0, defeat: 1},
    {id: 2, name: "Carl", win: 2, defeat: 1}
]

如何使用键“name”作为参考分组或合并为类似的内容:

data = [
    {id: 1, name: "Amy", win: 2, defeat: 3},
    {id: 2, name: "Carl", win: 2, defeat: 2}
]

已修改我忘了提及我的ID也无法添加。

3 个答案:

答案 0 :(得分:5)

这是我的尝试

#!/usr/bin/env ruby

data = [
    {"name"=> "Amy", "win" => 1, "defeat" => 0},
    {"name"=> "Amy", "win" => 1, "defeat" => 3},
    {"name"=> "Carl", "win" => 0, "defeat" => 1},
    {"name"=> "Carl", "win" => 2, "defeat" => 1}
]

merged_hash = data.group_by { |h| h['name'] }.map do |_,val| 
  val.inject do |h1,h2| 
    h1.merge(h2) do |k,o,n|
      k == 'name' ? o : o + n 
    end
  end
end

merged_hash
# => [{"name"=>"Amy", "win"=>2, "defeat"=>3},
#     {"name"=>"Carl", "win"=>2, "defeat"=>2}]

回答已编辑的帖子: -

#!/usr/bin/env ruby

data = [
    {id: 1, name: "Amy", win: 1, defeat: 0},
    {id: 1, name: "Amy", win: 1, defeat: 3},
    {id: 2, name: "Carl", win: 0, defeat: 1},
    {id: 2, name: "Carl", win: 2, defeat: 1}
]

merged_hash = data.group_by { |h| h.values_at(:name, :id) }.map do |_,val| 
  val.inject do |h1,h2| 
    h1.merge(h2) do |k,o,n|
      %i(id name).include?(k) ? o : o + n 
    end
  end
end

merged_hash
# => [{:id=>1, :name=>"Amy", :win=>2, :defeat=>3},
#     {:id=>2, :name=>"Carl", :win=>2, :defeat=>2}]

答案 1 :(得分:1)

您可以使用each_with_object和具有适当默认值的哈希备忘录一次性完成此操作。例如:

data.each_with_object(Hash.new { |h, k| h[k] = { :id => k.first, :name => k.last, :win => 0, :defeat => 0 } }) do |h, m|
  k = h.values_at(:id, :name)
  m[k][:win   ] += h[:win   ]
  m[k][:defeat] += h[:defeat]
end.values

基本技巧是缓存由适当的密钥(在这种情况下为[ h[:id], h[:name] ])索引的结果,并使用这些值来存储您之后的内容。 m Hash上的默认proc会自动验证缓存的值,然后您可以在迭代期间应用简单的求和。最后values调用解包缓存。

答案 2 :(得分:0)

您可以使用group_by

的好地方
result = []
data.group_by{|d| d[:id]}.each do {|name, records|
  win = 0
  defeat = 0

  records.each do |r|
    win += r[:win]
    defeat += r[:defeat]
  end
  f = records.first
  results << {:id => f[:id], :name => f[:name], :win => win, :defeat => defeat}
end