tags:

views:

66

answers:

1

I'm confused, I have @quote.quote_line_items and this is an array of items like this:

[{id: 85, part_number: "X67AC0M08", short_description: "X67 Threaded Caps M8, 50 pieces", list_price: "18.00", arg_cost: "12.15", long_description: "X67 Threaded Caps M8, 50 pieces", created_at: "2009-11-27 20:29:58", updated_at: "2009-11-27 20:29:58", quote_id: 1259353798}, {...}]

Consider if many items like this are in an array, how can I get, say, all of the list_price values summed up.

Is there a simple method to get the sum of all the list_price values by key?

+4  A: 

Given the array = [itemA, ...], and each item has method list_price, then you can do that:

sum = array.map{|i|i.list_price}.reduce(:+)

or

sum = array.reduce(0) {|sum,item| sum + item.list_price }

If each item is hash, and you want to get values from :list_price, then try this:

sum = array.reduce(0) {|sum,item| sum + item[:list_price].to_f }

Note: edited after you corrected the example in question

MBO
Douglas F Shearer
@Douglas Actually it was all wrong, don't know where i get it from :-) I fixed it now
MBO