我有像这样的红宝石哈希
[{user_id: 3, purchase: {amount: 2, type_id:3, name:"chocolate"}, {user_id: 4, purchase: {amount: 1, type_id:3, name: "chocolate"}, {user_id: 5, purchase: {amount: 10, type_id:4, name: "penny-candy"}]
我想通过type_id获取数组并合并,将金额相加,将用户连接到金额,因此最终结果将是
[{type_id: 3, name: "chocolate", total_amounts:3, user_purchases[{user_id:3, amount:2},user_id:4,amount:1}], {type_id:4, name: "penny-candy", total_amounts: 10, [{user_id:5,amount:2}]}]
我如何从一种输出转到另一种?
答案 0 :(得分:1)
这是一个group_by问题。我会给你2:
new_array = old_array.group_by{|x| x[:purchase][:type_id]}.values.map do |group|
{:type_id => group[0][:purchase][:type_id], :total_amounts => group.map{|g| g[:purchase][:amount]}.reduce(&:+)}
end
将其他2作为练习
答案 1 :(得分:0)
我首先要简化它:
old_arr = [
{user_id: 3, purchase: {amount: 2, type_id:3, name:"chocolate"}},
{user_id: 4, purchase: {amount: 1, type_id:3, name: "chocolate"}},
{user_id: 5, purchase: {amount: 10, type_id:4, name: "penny-candy"}}]
intermediate_arr = old_arr.map{ |h| [h[:user_id], h[:purchase][:amount], h[:purchase][:type_id], h[:purchase][:name]]}
这会创建以下数组:
[[3, 2, 3, "chocolate"], [4, 1, 3, "chocolate"], [5, 10, 4, "penny-candy"]]
现在您可以以任何方式格式化它。我选择像这样格式化:
new_hash = {}
intermediate_arr.each do |arr|
if new_hash[arr[2]]
new_hash[arr[2]][:purchase] += [{user_id: arr[0], amount: arr[1]}]
else
new_hash[arr[2]] = {name: arr[3], purchase: [{user_id: arr[0], amount: arr[1]}]}
end
end
,并提供:
{3=>{:name=>"chocolate", :purchase=>[{:user_id=>3, :amount=>2}, {:user_id=>4, :amount=>1}]}, 4=>{:name=>"penny-candy", :purchase=>[{:user_id=>5, :amount=>10}]}}