我有一个包含哈希值的数组。如果它们具有相同的 key ,我只想添加其值。
@receivers << result
@receivers
=> [{:email=>"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="70050315022f404230091f021c1f1f1b5e131f1d" rel="noreferrer noopener nofollow">[email protected]</a>", :amount=>10.00}]
result
=> {:email=>"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="34414751466b0406744d5b46585b5b5f1a575b59" rel="noreferrer noopener nofollow">[email protected]</a>", :amount=>7.00}
我希望上面的结果看起来像这样
[{:email=>"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a4a2b4a38ee1e391a8bea3bdbebebaffb2bebc" rel="noreferrer noopener nofollow">[email protected]</a>", :amount=>17.00}]
有人知道如何做到这一点吗?
这是整个方法
def receivers
@receivers = []
orders.each do |order|
product_email = order.product.user.paypal_email
outfit_email = order.outfit_user.paypal_email
if order.user_owns_outfit?
result = { email: product_email, amount: amount(order.total_price) }
else
result = { email: product_email, amount: amount(order.total_price, 0.9),
email: outfit_email, amount: amount(order.total_price, 0.1) }
end
@receivers << result
end
end
最佳答案
@receivers.group_by {|h| h[:email]}.map do |k, v|
{email: k, amount: v.inject(0){|s,h| s + h[:amount] } }
end
# => [{:email=>"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ffafceafdd0bfbdcff6e0fde3e0e0e4a1ece0e2" rel="noreferrer noopener nofollow">[email protected]</a>", :amount=>17.0}]
@receivers.each_with_object(Hash.new(0)) {|h, nh| nh[h[:email]]+= h[:amount] }.map do |k, v|
{email: k, amount: v}
end
关于ruby - 带哈希的数组,如何合并相同的键并添加其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37003362/