I want to retrieve a hashmap from a mongoid group_by instead of a array
Product.group_by {|p| p.user_id }
returns an array of mappings
result = Product.group_by {|p| p.user_id }
=> [ {"12354asdf" => [product1, product2, product3]},
{"safakjgh314" => [product4, product5, product6]} ]
I'm currently running the result of this query over the following to achieve a single hash of mappings
result.reduce Hash.new, :merge
=> {"12354asdf" => [product1, product2, product3], "safakjgh314" => [product4, product5, product6]}
is there a more efficient way to do this?
edit*** After grouping I'd rather operate over the collection with an enumerable that makes sense.
result.each do |k v| k v end
rather than
result.each do |h| h.keys.first, h.values.first end
example of what it currently returns.
[
{user_object => [item1, item2, item3] },
{user2_object => [item1, item2, item3] },
{user2_object => [item1, item2, item3] }
]
Regarding the more compact way to iterate over the array of hashes, you can take each element's first
:
result.map(&:first).each do |k, v|
puts k
puts v.count
end
# 12354asdf
# 3
# safakjgh314
# 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With