Ruby Ruby Collections Ruby Hashes Working with Hash Keys

ALex Chew
PRO
ALex Chew
Pro 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,816 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,816 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.