0

我有一个 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是股票上可用的公司符号company.symbol。这可能吗?

4

2 回答 2

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
于 2012-10-18T10:31:08.827 回答
0
hash = {}
shares.each{ |share|
  hash[share.company.symbol] = [] unless hash[share.company.symbol]
  hash[share.company.symbol] << share
}
于 2012-10-18T10:33:24.427 回答