Ruby Ruby Collections Ruby Hashes Working with Hash Values

julianordhem
julianordhem
4,060 Points

Using the has_value? method, check to see if the grocery_item hash has a value called "Bread". If it does, set a new key

I don't know what I'm doing wrong help!

hash.rb
grocery_item = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company"}

if
grocery_item.has_value?("Bread")
grocery_item = {"food" => "true"}
end

2 Answers

Ari Misha
Ari Misha
19,202 Points

Hiya there! The challenge seems simple enough and straightforward. In the task 1, you need to set food key to true, if grocery_item hash contains value "Bread". And in the task 2, you need to use values_at method in Ruby to get the value at the key item in the grocery_item hash, and store the result in grocery_list variable. Here is how your code should look like:

grocery_item = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company" }

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

~ Ari

alan santos
alan santos
4,125 Points

Thank you very much Ari! It was really helpful.

Samuel Ferree
Samuel Ferree
31,709 Points

you're checking the hash correctly, but you're adding a new key/value pair incorrectly.

when you're adding a new key/value pair to a ruby hash that is already declared, use the syntax hash[key] = value;

see below:

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