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

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,947 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")