Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby

ROBERT ROBINSON
ROBERT ROBINSON
7,723 Points

Ruby Monk

Im on Primer Ruby section 4.1 ( HASHES )

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

This is what passed the section. My question is. When changing the price of a menu item by 10% , why do we call.

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

and not

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

???

This confuses me . Why do we have to call on the item and not the price?

2 Answers

Nelly Lam
Nelly Lam
5,098 Points

In a hash, one way to access the value of a key-value pair is this:

hash_name[key]

This just returns the value at that key.

So when you say restaurant_menu[item], you will get the price. It's similar to when you want the value inside an array, where you would write array_name[index].

But what you're doing is not just accessing the value at that key, you are assigning a new price (one that is + 10%) to that item.

ROBERT ROBINSON
ROBERT ROBINSON
7,723 Points

Ok.. I see it now. I split up the Hash into Item / Price I pull the Item part and it modifies the Value.

Duh. I totally see it now. Thank you !