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

Josh Calkins
Josh Calkins
3,623 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

Does anyone know how to go about answering this question? I'm sure I'm missing something obvious but I am completely stumped.

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

4 Answers

so it took me a couple of times of watching the videos to get the answer for this. What you need to do is use an if statement and if it is true add the key food to the array. it should look like this

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

first line

if grocery_item.has_value?("Bread")

2nd line

  grocery_item["food"] = true

3rd line

end

hope this helps

David Borrero
David Borrero
3,089 Points

This code worked for me:

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

if grocery_item.has_value?("Bread") == true

  grocery_item.store("food", true)

end

For this you may want to use an if statement with the definition using the .has_value? method and in the argument creating the new key.

if grocery_item.has_value?("Bread")
  hash = {"New_key" => "New_value"}

Hey Josh,

The code that worked for me is:

grocery_item.store("food", true) if grocery_item.has_value?("Bread")