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

Code challenge : has_value? method

I have problems in this code challenge. Here is my code:

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

Please help me with that.

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

3 Answers

Arturo Alviar
Arturo Alviar
15,739 Points

Hi Leonardo,
What you want to do in your code is add a conditional statement
The has_value? function returns a boolean so you should use that to determine whether to add food or not
Another thing, you are not adding food as a key to the hash. All you are doing is setting a variable name food to the value of true.

Here is how I approached it:

#only add food as a key if there is a key named Bread in the grocery_item hash
grocery_item["food"] = true if grocery_item.has_value?("Bread") 

Hope that helps!

Christie Metson
Christie Metson
10,837 Points

Yes, helps heaps thank you :)

Christie Metson
Christie Metson
10,837 Points

Thanks Arturo, that worked great! Do you by any chance know why it didn't work for me when I had my code round the other way? Here's how I had it:

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

Arturo Alviar
Arturo Alviar
15,739 Points

That is because you cannot assign a statement a value.
What your code is trying to do there is set if grocery_item.has_value?("Bread") grocery_item["food"] to have the value true. That is an illegal statement.
As you know, we want grocery_item["food"] to have the value true. That is why that goes first. Another way to write it would be

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

Hope this helps!