Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby

Working with Hash Keys(has_key? code challenge)

Using the has_key? method, check if the hash variable has a key called "calories". If it does, set a new variable called "food" to true.

hash = { "name" => "Bread", "quantity" => 1, "calories" => 100 }
if hash.has_key?("calories")
  hash["food"] = true
end

Not entirely sure what I'm doing incorrectly. The error I keep getting is that "the food variable is not found" I've also tried this using the store method:

if hash.has_key?("calories")
  hash.store("food", true)
end

Any help would be great.

2 Answers

Hi Michael,

food should be a new variable that you set to true, not added as a key to the hash.

food = true

Appreciated, thank you very much.

Noah Yasskin
Noah Yasskin
23,945 Points

I had a similar challenge. I wanted to use hash.store("food", true) like the video but it wants something simpler:

hash = { "name" => "Bread", "quantity" => 1, "calories" => 100 } food = true if hash.has_key?("calories")