假设您有:
new_array_of_hashes = [
{ keyword: 'foo', total_value: 1 },
{ keyword: 'bar', total_value: 2 },
{ keyword: 'bar', total_value: 4 },
{ keyword: 'foo', total_value: 3 },
]
现在我们将逐步检查您的代码:
combined_keywords = new_array_of_hashes.each_with_object(Hash.new(0)){|oh, newh|
newh[oh[:keyword]] += oh[:total_value].to_f
}
这将遍历数组中的每个散列。我们还设置了一个新的哈希,0
如果我们访问一个不存在的键,它会返回:
# Pass 1
oh = { keyword: 'foo', total_value: 1 }
newh = {}
newh[ oh[:keyword] ] #=> newh['foo'] This key doesn't exist and returns 0
oh[:total_value].to_f #=> 1.to_f => 1.0
newh[oh[:keyword]] += oh[:total_value].to_f
#=> newh['foo'] = newh['foo'] + oh[:total_value].to_f
#=> newh['foo'] = 0 + 1.0
# Pass 2
oh = { keyword: 'bar', total_value: 2 }
newh = { 'foo' => 1.0 }
newh[ oh[:keyword] ] #=> newh['bar'] This key doesn't exist and returns 0
oh[:total_value].to_f #=> 2.to_f => 2.0
newh[oh[:keyword]] += oh[:total_value].to_f
#=> newh['bar'] = newh['bar'] + oh[:total_value].to_f
#=> newh['bar'] = 0 + 2.0
现在,由于我们有接下来两次迭代的密钥,我们可以正常访问事物:
# Pass 3
oh = { keyword: 'bar', total_value: 4 }
newh = { 'foo' => 1.0, 'bar' => 2.0 }
newh[ oh[:keyword] ] #=> newh['bar'] This key now exists and returns 2.0
oh[:total_value].to_f #=> 4.to_f => 4.0
newh[oh[:keyword]] += oh[:total_value].to_f
#=> newh['bar'] = newh['bar'] + oh[:total_value].to_f
#=> newh['bar'] = 2.0 + 4.0
# Pass 4
oh = { keyword: 'foo', total_value: 3 }
newh = { 'foo' => 1.0, 'bar' => 6.0 }
newh[ oh[:keyword] ] #=> newh['foo'] This key now exists and returns 1.0
oh[:total_value].to_f #=> 3.to_f => 3.0
newh[oh[:keyword]] += oh[:total_value].to_f
#=> newh['foo'] = newh['foo'] + oh[:total_value].to_f
#=> newh['foo'] = 1.0 + 3.0
当块返回时,它将返回newh
;这就是each_with_object
工作原理。
如您所见,返回的是表单的哈希:
{ 'foo' => 4.0, 'bar' => 6.0 }
所以这只是一个组合数组,其中新键是存储的:keyword
对象,值是总和。
基于您的新哈希表
{
keyword: "ACTUAL_KEYWORD",
total_value: ACTUAL_TOTAL_VALUE,
revenue_per_transaction: ACTUAL_REVENUE
}
这种格式没有多大意义。因为哈希只有键:值对。您可能需要有一个子哈希的哈希,或者循环运行两次。一次:total_value
又一次:revenue_per_transaction
。这真的取决于你想要你的最终对象是什么。
编辑:
根据您新的预期输入和输出,您可以使用:
sum_keys = [:total_value, :revenue_per_transaction]
new_array_of_hashes.group_by{ |h| h[:keyword] }
.map{ |keyword, related|
tmp = {keyword: keyword}
tmp.merge! Hash[sum_keys.zip Array.new(sum_keys.size, 0)]
related.reduce(tmp){ |summed, h|
sum_keys.each{ |key| summed[key] += h[key] }
summed
}
}
#=> [
# { keyword: 'foo', total_value: 4, revenue_per_transaction: 10 },
# { keyword: 'bar', total_value: 6, revenue_per_transaction: 8 },
#]
有点乱。我可能map
会将调用的作用重构为它自己的辅助方法。我提供起始值的原因reduce
是因为否则它将使原始哈希从new_array_of_hashes
.