Ruby Ruby Collections Ruby Hashes Working with Hash Keys

Dharma Teja
PRO
Dharma Teja
Pro Student 5,206 Points

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

i hve tried in all ways but i'm not getting it.

hash.rb
hash = { "name" => "Bread", "quantity" => 1, "calories" => 100 }
if hash.has_key?("calories")
  #do something
  hash.store{"food" => ture}
end

3 Answers

Jay McGavren
STAFF
Jay McGavren
Treehouse Teacher

The full challenge text is:

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.

The code you posted is trying to set a key named "food" within the hash. The challenge actually wants you to set a completely separate variable named food.

Jay McGavren
STAFF
Jay McGavren
Treehouse Teacher

Jeff Delacruz , in the line:

"food" = true

...it's attempting to assign a new value to the string "food", which is not valid code. If you remove the quotes, you'll be assigning to a variable named food, which is what you want.

Jeff Delacruz
Jeff Delacruz
2,043 Points

I got it Jay. Thanks for the quick response

Jay McGavren
STAFF
Jay McGavren
Treehouse Teacher

Dharma Teja , sorry I didn't see your question before; hopefully you've already gotten an answer. But in case anyone has a similar question...

The task is to "set a variable", which in Ruby means that you just want this code:

food = true

There's no need to set a value for a hash key or anything like that.