0

我有一个像这样的红宝石哈希

[{user_id:3,购买:{金额:2,type_id:3,名称:“巧克力”},
 {user_id:4,购买:{数量:1,type_id:3,名称:“巧克力”},
 {user_id:5,购买:{数量:10,type_id:4,名称:“penny-candy”}]

我想获取数组并按 type_id 合并,对金额求和,将用户连接到金额,所以最终结果是

[{type_id: 3, name: "巧克力", 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}]}]

我将如何从一种类型的输出转到另一种类型的输出?

4

2 回答 2

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

剩下的两个留作练习

于 2012-06-18T06:51:23.670 回答
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}]}}
于 2012-06-18T06:27:27.753 回答