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 trialDouglas Eisner
2,756 Pointsadd key, value pair to existing hash?
Unable to add a key, value pair to existing hash for exercises in Ruby Collections.
grocery_item.merge!(name: "true)
grocery_item = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company" }
if grocery_item.has_value?("bread")
grocery_item.merge!(food: true)
end
h = {}
h.merge!(key: "bar")
1 Answer
Steve Hunter
57,712 PointsHi Douglas,
The has_value?
method returns true
if the object it is called upon, in this case the grocery_item
hash, contains the value that you specify; Bread
in this case.
You need to add the new pairing to the grocery_list
hash, and you need to create a new key, "food
" and assign it a value of true
.
That could look like:
grocery_item = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company" }
if grocery_item.has_value?("Bread")
grocery_item["food"] = true
end
Or you can do this in one line:
grocery_item["food"] = true if grocery_item.has_value?("Bread")
I hope that helps,
Steve.