[英]How can I sort a Ruby array into a hash from a key?
I have a Ruby array which looks like: 我有一个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">
]
How could I sort it by the key company.symbol
(which is a Mongoid relation, and present in every Share object), so it ends up into a hash like 我如何通过关键的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">]
}
where aapl
and msft
are company symbols available on a Share's company.symbol
. 其中aapl
和msft
是在Share的company.symbol
上可用的公司符号。 Is this possible? 这可能吗?
Not exactly what I asked, but works as I wanted: 并非完全符合我的要求,但可以按我的意愿工作:
@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.