Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Collections Ruby Hashes Working with Hash Values

Setting a new key in a hash after using the .has_value method

I'm stuck on this code challenge where we check the contents of the hash to see if they include a value called "Bread". If it does contain the value (it does) we are to add a new key "food" and set its value to "true". I keep getting errors with this, the most current error you see below is ArgumentError: 1 for 2. I tried an if statement and no dice. Any suggestions? I feel like this should be relatively straightforward. Thanks!

hash.rb
grocery_item = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company" }

grocery_item.has_value?("Bread")

grocery_item.store( "food" => "true" )
Charles Smith
Charles Smith
7,575 Points

Okay, check out this link

Based on that, I would say the syntax you have above is wrong, and should be:

grocery_item.store(:food, "true")

Found the answer in a forum, guess I didn't look hard enough! I tried an if statement before but didn't include the new key and value pair within the if statement. Here's the correct code:

if grocery_item.has_value?("Bread") grocery_item.store("food", true) end

Thanks for your responses!

2 Answers

Charles Smith
Charles Smith
7,575 Points

Stack's got your back.

Syntax error, basically.

Add to a hash:

hash[:key] = value

So you want:

grocery_item[:food] = true

Hi Charles, Thanks for your response! I just tried it and got the error message: "The key 'food' was not found within the hash."

Charles Smith
Charles Smith
7,575 Points

Sorry, possibly need quotes around true. Couldn't remember if it was formatted that way or not since I was using a Boolean.

Yep, I tried it both ways and no dice.

Damian Irarrazaval
Damian Irarrazaval
2,707 Points

Those codes do the same? Why the second throws me error?

if grocery_item.has_value?("Bread") 
grocery_item.store("food", true)
end 

if grocery_item.has_value?("Bread")
grocery_item[:food] = true 
end