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

Yuichi Narisawa
Yuichi Narisawa
19,548 Points

How to use "has_value?" at string?

I assume "has_value?" search for the "value", right? Then, how can I use this method to search string like this code challenge? Does this code work if I wrote "has_key?"?

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

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

1 Answer

Hi there,

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 are correct that has_key? also exists.

In your code, you have called the method correctly. However, your statement inside the if conditional isn't quite right. You need to add the new pairing to the grocery_list hash, not just set a variable to true. 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

I hope that helps,

Steve.

Yuichi Narisawa
Yuichi Narisawa
19,548 Points

Hi, Steve! Thank you for your quick response. I really appreciate it!

No problem! :+1: :smile: