2012-06-18 169 views
0

執行總和我有一個紅寶石散列這樣紅寶石散列組和量

 
[{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

只是出於好奇,有沒有具體的理由讓你使用數組? 您可以使用類似於{3 => {name:「chocolate」,total_amounts:3,user_purchases [{user_id:3,amount:2},user_id:4,amount:1}]}, {4 => {name:「penny-candy」,total_amounts:10,[{user_id:5,amount:2}]}}'這會讓事情變得更簡單。 – Amir

+0

@AmirF,它是從MySQL出來的,所以對象被表示爲一個數組。我不知道有另一種方法可以做到這一點。 – pedalpete

回答

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作爲練習

+0

非常好,乾淨。我認爲這是一個分組錯誤,但需要推動。謝謝 – pedalpete

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}]}}