Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoid group_by return a hashmap instead of array of hashes

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] }
]
like image 214
Stephen Nguyen Avatar asked Oct 21 '22 16:10

Stephen Nguyen


1 Answers

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
like image 170
Uri Agassi Avatar answered Nov 02 '22 12:11

Uri Agassi