2012-10-18 14 views
0

나는 보이는 루비 배열이 같은 :루비 배열을 키의 해시로 정렬하려면 어떻게해야합니까?

[ 
    #<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"> 
] 

나는 (모든 공유 객체에 존재하는 Mongoid 관계이며,) 키 company.symbol하여 정렬 그래서 같은 해시로 끝나는 수있는 방법

{ 
    :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 
} 
관련 문제