randombits
randombits

Reputation: 48450

Iterate over a hash using keys from an array, and sum the results

I have a Hash that indexes a bunch of IDs to a value, something like:

hash = {1: 3.00, 2: 4.00, 3: 2.00, 4: 15.00, 5: 12.00, 6: 1.00}

I have an Array that looks like:

arr = [2, 3, 6]

What's a short, Ruby idiomatic way to iterate over my Array and add up the cumulative total from the corresponding keys in the Hash?

The result of the above would equal:

4.00 + 2.00 + 1.00 == 7.00

Upvotes: 1

Views: 510

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110685

hash = {1=>3.0, 2=>4.0, 3=>2.0, 4=>15.0, 5=>12.0, 6=>1.0}
arr = [2, 3, 6]

arr.reduce(0) { |t,e| t + hash[e] }
   #=> 7.0

Upvotes: 1

rohit89
rohit89

Reputation: 5773

arr.map {|i| hash[i]}.reduce(:+)

Upvotes: 0

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

You probably can't get any more ruby-ish than this :)

hash.values_at(*arr).reduce(:+)

Upvotes: 9

Related Questions