I have an array of objects obtained from some queries and the all the object have the attributes: id, title and quantity. The question is : How can I sum the quantity by id and save each fields? I've tried this snippet
h=Hash.new(0)
a.each do |el|
h[el.id] += el.quantity
end
and this goes, but I lose the title! How can I have the title inside the hash h?
thanks!
UPDATE to a solution:
I thought that the data for the a array could be many thousands of records, so I decided to anticipate the aggregation to sum the quantity. Thank's to a example of solution of , now each time I get the block of records from master table, I elaborate the data in this way
@agg = Hash.new(Array.new)
master.scope.each do |mst|
recs = mst.select.........
recs.each do |el|
store = @agg[el.id].empty? ? 0 : @agg[el.id][1]
@agg[el.id] = [el.title, el.quantity+store]
end
end
at the end, @agg holds all and only the aggregated data.
If someone can provide a more general or elegant solution come forward.
Thank's to all.
Giorgio