John-David Sayle
John-David Sayle

Reputation: 3

Rubymonk - Iterating over a hash

Ruby Monk (Section: 4.1 - Hashes) has an exercise about a restaurant and increasing the price by 10%. The directions on the site are:

Use the each method to increase the price of all the items in the restaurant_menu by 10%.

Remember: in the previous example we only displayed the keys and values of each item in the hash. But in this exercise, you have to modify the hash and increase the value of each item.

My main question is, why does this code pass:

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

vs. this?

restaurant_menu = { "Ramen" => 3, "Dal Makhani" => 4, "Coffee" => 2 }
# write the each loop here. 
restaurant_menu.each do | item, price |
  puts "#{item}: $#{price + (price * 0.1)}" 
end

I'm assuming it has something to do with [item] which I'm assuming is an array(?) and "price + (price * 0.1)" being added to the [item] array.

Secondarily, is it possible that the string interpolation could be making the above code not pass . . . Thanks in advance for anything in helping me better understand this code.

Upvotes: 0

Views: 142

Answers (1)

Cristiano Mendonça
Cristiano Mendonça

Reputation: 1282

When you execute this:

restaurant_menu[item] = price + (price * 0.1)

you are assigning the new price to the key of the hash (which will store the new value - you can check it by calling restaurant_menu[item]).

When you execute this:

 puts "#{item}: $#{price + (price * 0.1)}"

you are assigning the new price to nowhere (which will remain the same when you call restaurant_menu[item]).

Thus you're not changing your hash and the code won't pass validation.

Upvotes: 1

Related Questions