What is the best way to sum hash values in ruby:
@price = { :price1 => "100", :price2 => "100", :price3 => "50" }
I do something like this right now:
@pricepackage = @price[:price1] + @price[:price2] + @price[:price3] + 500
Please explain your answer, I want to learn why and not just how. =)
You can do:
EDIT: adding explanation
So @price.values returns an array that collects all the values of the hash. That is for instance
["1", "12", "4"]. Then.map(&:to_i)appliesto_ito each of the elements of this array and thus you get[1,12,4]. Lastly.inject(0,&:+)preforms inject with initial value 0 and accumulating using the function+, so it sums all the elements of the array in the last step.