Wednesday, 11 September 2013

rails: array of objects, how to sum values of object attributes?

rails: array of objects, how to sum values of object attributes?

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!

No comments:

Post a Comment