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

Douglas Eisner
Douglas Eisner
2,756 Points

add 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)

h = {}
h.merge!(key: "bar")

1 Answer

Hi 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

Or you can do this in one line:

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

I hope that helps,