![](/img/trans.png)
[英]How can I sort ruby hash with string key by setting priority to the key elements?
[英]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">]
}
其中aapl
和msft
是在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.