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 trialNithin Rajan
1,737 PointsUsing 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 = { "name" => "Bread", "quantity" => 1, "calories" => 100 }
hash.has_key?("calories")
hash["food"] = "true"
2 Answers
Steve Hunter
57,712 PointsHi 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.
Zim Mayfield
2,621 PointsThank you, I just forgot the parentheses after my if. you the man!
Nithin Rajan
1,737 PointsNithin Rajan
1,737 PointsHey Steve,
Thanks for the help Steve.
Nithin
Steve Hunter
57,712 PointsSteve Hunter
57,712 PointsGlad it worked for you. :-)