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

Jennifer Hsueh
Jennifer Hsueh
648 Points

not sure what the question is asking

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.

not sure what the question wants me to do: "If it does, set a new variable called food to true." does it want me to create a new hash variable?

hash.rb
hash = { "name" => "Bread", "quantity" => 1, "calories" => 100 }
hash.has_key?("calories")
food = { "name" => "Bread", "quantity" => 1, "calories" => true }
food.has_key?("calories")

6 Answers

Antonio De Rose
Antonio De Rose
20,884 Points

one, when you post code, please make sure, you use markdown, so it comes likes with a nice screen print, where the readability is high

hash = { "name" => "Bread", "quantity" => 1, "calories" => 100 } 
if hash.has_key?("calories")  #I will help you with this line by adding if in front, cause it is asking you to check
food = { "name" => "Bread", "quantity" => 1, "calories" => 100 } #why did you put this line, take it off
food == hash # this is how you not assign to a variable # food = true
end #add this end too

#I have done the coding for you, now clean the code, by taking off the line
#which is not needed and try it
Antonio De Rose
Antonio De Rose
20,884 Points
hash = { "name" => "Bread", "quantity" => 1, "calories" => 100 }
hash.has_key?("calories") # this line is correct
# just have to continue, from the right above line to ask it with 
# if followed by - hash.has_key?("calories")
# set it into variable as mentioned by the question
#then end it

food = { "name" => "Bread", "quantity" => 1, "calories" => true } #this line is not necessary
food.has_key?("calories") #this line is not necessary
Jennifer Hsueh
Jennifer Hsueh
648 Points

Thanks for your response Antonio! but how do i set it into a variable? like create a new hash called food?

Antonio De Rose
Antonio De Rose
20,884 Points

please send me the new complete code you have tried

Jennifer Hsueh
Jennifer Hsueh
648 Points
hash = { "name" => "Bread", "quantity" => 1, "calories" => 100 } 
if hash.has_key?("calories") 
   food = true
end 
Ana María Benites Rodríguez
Ana María Benites Rodríguez
1,011 Points

Hi Jennifer! Hi food = true? and not hash.store("food", true) ? thanks!