I need to sum values in an array hashes and I found a way to do it here
but it sure seems like there should be a more elegant way in Ruby.
Here is what works;
sales = [{"sale_price"=>210000, "deed_type"=>"Warranty Deed"}, {"sale_price"=>268300, "deed_type"=>"Warranty Deed Joint"}]
total_sales = sales.inject(0) {|sum, hash| sum + hash["sale_price"]}
The totals line is not very readable. It would be nice if something like this worked;
total_sales = sales.sum("sale_price")
Is this just wishful thinking or am I overlooking a better solution?
Enumerable#sumyou'd like and problem solved. Maybe you should call itEnumerable#hash_sumthough, Ruby is a OOP language andsumshould be calling methods.