我有一系列哈希(已编辑):
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,无法添加。
这是我的尝试
#!/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}]
您可以使用each_with_object
和具有适当默认值的Hash-memo一次性完成。例如:
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
调用解包缓存。
你可以使用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