Rubymonk - 遍历哈希

Rubymonk - Iterating over a hash

Ruby Monk(部分:4.1 - 哈希)有一个关于餐厅的练习,将价格提高 10%。网站上的指示是:

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.

我的主要问题是,为什么这段代码通过了:

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

对比这个?

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

我假设它与 [item] 有关,我假设它是一个数组 (?) 并且“price + (price * 0.1)”被添加到 [item] 数组。

其次,字符串插值是否可能导致上述代码无法通过。 . .在此先感谢帮助我更好地理解这段代码的任何事情。

当您执行此操作时:

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

您正在将新价格分配给散列的键(它将存储新值 - 您可以通过调用 restaurant_menu[item] 来检查它)。

当您执行此操作时:

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

您正在将新价格分配给任何地方(调用 restaurant_menu[item] 时将保持不变)。

因此您没有更改您的散列,代码将无法通过验证。