Ruby Ruby Collections Ruby Hashes Working with Hash Keys

Richard Poirier
Richard Poirier
Pro Student 2,930 Points

How do you set variables to be true if something is present in a hash

I have been working on this challenge for some time and I can't figure it out...I totally get how to search a hash for a key, but how do you write the code following it to make a new variable called food = true if the key is present? The attached code as just my last ditch effort to figure it out....

hash = { "name" => "Bread", "quantity" => 1, "calories" => 100 }
if hash.fetch("calories")

1 Answer

Hi Richard,

You're close but you want the result of the has_key? method to be the condition for your if statement.

if hash.has_key?("calories")
  # set a variable named food to true

Also, be careful with the assignment. It's a variable named food and not a string containing Food