1

I'm going through the RubyMonk exercises on hashes The exercise is to change the prices of the restaurant_menu by 10%. My solution was incorrect. I iterated over each tuple and changed just the price value.

restaurant_menu = { "Ramen" => 3, "Dal Makhani" => 4, "Coffee" => 2 }
restaurant_menu.each do |item, price|
  price = price * 1.1
end

The correct solution is here. restaurant_menu = { "Ramen" => 3, "Dal Makhani" => 4, "Coffee" => 2 } restaurant_menu.each do |item, price| restaurant_menu[item] = price + (price * 0.1) end

I don't understand why the extra call to the hash is necessary if I'm already iterating over the price values.

jingyang81
  • 453
  • 1
  • 4
  • 7
  • I don't know much ruby, but I expect that in your original code you were simply updating the local (stack) variable 'price', and not the value that is stored in the hash table. – Alex Aug 20 '13 at 19:04
  • Alex. You mean there's a local variable for price independent of the one in the hash-table? – jingyang81 Aug 24 '13 at 02:35
  • Yes, that is what I mean, a variable on the stack that gets assigned the value pulled out of the hash table during each iteration. i.e. not the same memory location (reference, pointer, pick your preferred terminology) as the 'price' field in the hash table. – Alex Aug 24 '13 at 02:52

1 Answers1

0

You're not updating the original hash. To update the original hash you should do this:

restaurant_menu.each do |key, value|
  restaurant_menu[key] = value * 1.1
end

I renamed to item, price to key, value to make clear what is going on here. I hope this makes sense. If not, please leave a comment.

Mischa
  • 42,876
  • 8
  • 99
  • 111