2012-10-18 36 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 
} 
相关问题