Reputation: 165
I have a hash like this.
products = {199 =>['Shoes', 59.99], 211 =>['Shirts', 19.99], 245 =>['Hats', 25.99], 689 => ['Coats', 99.99], 712 => ['Beanies', 6.99]}
It has an item number => [product, price]
.
I would like to sum up all the prices without using the inject method.
Can anyone help me please?
Upvotes: 8
Views: 9610
Reputation: 156434
This should work in any version of Ruby using only the built-in functions:
products.values.map(&:last).reduce(&:+) # => 212.95
Upvotes: 0
Reputation: 35308
Why without using inject? Inject is exactly what you want.
products.inject(0) { |total, (k, v)| total + v.last }
Sure, you can use a more procedural solution, but why?
Upvotes: 5