Ruby Ruby Collections Ruby Hashes Working with Hash Values

has_value

grocery_item = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company" } if grocery_item.has_value?("Bread") hash = {"food" => true} end

Q: Why the above code doesn;t work?

hash.rb
grocery_item = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company" }
if grocery_item.has_value?("Bread")
  hash =  {"food" => true}
end

1 Answer

Scott Wyngarden
PRO
Scott Wyngarden
Pro Student 16,699 Points

If you're looking to add the key/value pair of {"food" => true} to the grocery_item hash, change the bit that says

hash =  {"food" => true} 

to either

grocery_item["food"] = true

or

grocery_item = grocery_item.merge("food" => true)

or

grocery_item.merge!("food" => true)