1

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
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
randombits
  • 47,058
  • 76
  • 251
  • 433
  • 1
    This question was posted more than three weeks ago. It's interesting that no one has pointed out that `hash` is not a valid object. The syntax `{ 1: 2 }` is shorthand for `{:1=>2}`, but a symbol cannot begin with a digit. `{"1": 2}` would be OK, but I suspect you mean `( 1=>2 }`. Also there is no point in writing the values (floats) with two or more digits after the decimal with the last one being a zero, as Ruby will discard the final zero. – Cary Swoveland Nov 24 '15 at 07:04

3 Answers3

9

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

hash.values_at(*arr).reduce(:+)
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
1
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
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
  • I maintain that my way is more rubyish. Yours is likely more performant, but not as sexy. :) – Sergio Tulentsev Nov 24 '15 at 07:07
  • We can agree. See my comment on the question. – Cary Swoveland Nov 24 '15 at 07:08
  • Oh damn, never noticed the weird keys. – Sergio Tulentsev Nov 24 '15 at 07:10
  • Are you looking forward to another Moscow winter? I lived in Ottawa for a few years so can imagine what it's like. Skating on the canal was fun, but I hated the bitter cold, which seemed like it would never end. – Cary Swoveland Nov 24 '15 at 16:21
  • Moscow winter consists primarily of ruined shoes (because of all the chemicals they pour onto the roads to combat icing). A bit of skating, if you're lucky. But mostly ruined shoes and muddy puddles of half-thawed snow :) Am I looking forward to it? Hell no. :) – Sergio Tulentsev Nov 24 '15 at 16:44
0
arr.map {|i| hash[i]}.reduce(:+)
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
rohit89
  • 5,745
  • 2
  • 25
  • 42
  • 1
    While this answer is probably correct and useful, it is preferred if you [include some explanation along with it](http://meta.stackexchange.com/q/114762/159034) to explain how it helps to solve the problem. This becomes especially useful in the future, if there is a change (possibly unrelated) that causes it to stop working and users need to understand how it once worked. – Kevin Brown-Silva Oct 30 '15 at 21:44