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 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.

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.