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)

hash.rb
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
MOD
Steve Hunter
Treehouse Moderator 56,145 Points

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
end

Or you can do this in one line:

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

I hope that helps,

Steve.