2012-10-18 74 views
0

我有一個Ruby的陣列,它看起來像:如何將一個Ruby數組從一個鍵排序爲一個散列?

[ 
    #<Share _id: 507fd5a8ab432a6a35000006, _type: nil, price: {"cents"=>25535, "currency_iso"=>"USD"}, company_id: "507fcdb8ab432ac733000001", user_id: "507fcb06ab432a7c2e000001">, 
    #<Share _id: 507fd5a8ab432a6a35000007, _type: nil, price: {"cents"=>25535, "currency_iso"=>"USD"}, company_id: "507fcdb8ab432ac733000001", user_id: "507fcb06ab432a7c2e000002"> 
] 

我怎麼能在關鍵company.symbol(這是一個Mongoid關係,並在每一個共享對象存在)排序,所以它最終變成像哈希

{ 
    :appl => [#<Share _id: 507fd5a8ab432a6a35000006, _type: nil, price: {"cents"=>25535, "currency_iso"=>"USD"}, company_id: "507fcdb8ab432ac733000001", user_id: "507fcb06ab432a7c2e000001">] 
    :msft => [#<Share _id: 507fd5a8ab432a6a35000007, _type: nil, price: {"cents"=>25535, "currency_iso"=>"USD"}, company_id: "507fcdb8ab432ac733000001", user_id: "507fcb06ab432a7c2e000002">] 
} 

其中aaplmsft是一個分享的company.symbol公司提供的符號。這可能嗎?

回答

0

不正是我問過,但工程,我想:

@companies = current_user.shares.map { |s| s.company }.uniq.each do |company| 
    puts "#{company.name}: #{company.shares.map { |s| s if s.user == current_user and s.company == company }}" 
    # this prints all the shares of every company 
end 
0
hash = {} 
shares.each{ |share| 
    hash[share.company.symbol] = [] unless hash[share.company.symbol] 
    hash[share.company.symbol] << share 
} 
相關問題