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 trialHeather Stone
5,784 PointsSetting 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!
grocery_item = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company" }
grocery_item.has_value?("Bread")
grocery_item.store( "food" => "true" )
Heather Stone
5,784 PointsFound 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
7,575 PointsSyntax error, basically.
Add to a hash:
hash[:key] = value
So you want:
grocery_item[:food] = true
Heather Stone
5,784 PointsHi 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
7,575 PointsSorry, possibly need quotes around true. Couldn't remember if it was formatted that way or not since I was using a Boolean.
Heather Stone
5,784 PointsYep, I tried it both ways and no dice.
Damian Irarrazaval
2,707 PointsThose 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
Charles Smith
7,575 PointsCharles Smith
7,575 PointsOkay, 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")