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 Keys

ALex Chew
PLUS
ALex Chew
Courses Plus Student 154 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 already type in all as per instruct

hash.rb
hash = { "name" => "Bread", "quantity" => 1, "calories" => 100 }

hash.has_key?("calories") 

puts hash == food # => true 

3 Answers

Mike Hickman
Mike Hickman
19,817 Points

Hi Alex,

There are a couple things wrong.

  • Whenever you see the instructions for "do this if..." or "if this, then...", you are pretty safe to assume you'll need an if statement in your code.
if hash.has_key?("calories")
# do something
end
  • If it does have the key calories, it wants you to create a new variable called food (just like hash in the first line) and set it to true. This should go inside the if block, right? IF it has the key, then create the variable.
food = #what should go here?

Right now you're adding puts, which is to literally print out a string, which is not what it's asking you to do. Tweak these things and you'll pass.

Good luck!

Mike

Onyinye Chukwuneke
Onyinye Chukwuneke
814 Points

These were my two options: if hash.key?("calories") hash.store("food", true) end

or if hash.key?("calories") food = true end

Still not compiling.

Mike Hickman
Mike Hickman
19,817 Points

Hi Onyinye Chukwuneke

The challenge specifically wants you to use .has_key? method. Make sure to use

hash.has_key?

and not

hash.key?

The second way you did it is the correct way, just use the correct method and you will pass.

Have fun, Mike

Onyinye Chukwuneke
Onyinye Chukwuneke
814 Points

Hi Mike,

Still not compiling.

Me.