如何将Ruby数组从键中排序为哈希?

时间:2012-10-18 10:19:12

标签: ruby-on-rails arrays sorting hash mongoid

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

hash = {}
shares.each{ |share|
  hash[share.company.symbol] = [] unless hash[share.company.symbol]
  hash[share.company.symbol] << share
}