eddie tuell
eddie tuell

Reputation: 165

summing numbers in a hash in ruby

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

Answers (4)

megas
megas

Reputation: 21791

products.values.map(&:last).reduce(:+) #=> 212.95

Upvotes: 16

maerics
maerics

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

d11wtq
d11wtq

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

James
James

Reputation: 4807

sum = 0
products.each { |key, value| sum += value.last }

Upvotes: 1

Related Questions