簡體   English   中英

如何從鍵將Ruby數組排序為哈希?

[英]How can I sort a Ruby array into a hash from a key?

我有一個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關系,並存在於每個Share對象中)對它進行排序,所以它最終變成了像

{
    :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是在Share的company.symbol上可用的公司符號。 這可能嗎?

並非完全符合我的要求,但可以按我的意願工作:

@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
hash = {}
shares.each{ |share|
  hash[share.company.symbol] = [] unless hash[share.company.symbol]
  hash[share.company.symbol] << share
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM