Ruby Ruby Collections Ruby Hashes Working with Hash Keys

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

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

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

hash.has_key?("calories")
hash["food"] = "true"

1 Answer

Steve Hunter
MOD
Steve Hunter
Treehouse Moderator 57,656 Points

Hi there,

This needs two stages. First, see if there is a hash called calories. If there is, set a variable to true.

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

So, we test to see if the key "calories" is in the hash by using has_key?. If that returns true we move inside the if statement and set a new variable called food to true.

Remember, true is not a string in this case, it is a boolean, so no quotes are needed.

I hope that makes sense!

Steve.

Hey Steve,

Thanks for the help Steve.

Nithin