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

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"

2 Answers

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

Glad it worked for you. :-)

Thank you, I just forgot the parentheses after my if. you the man!