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,862 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,862 Points

please send me the new complete code you have tried

Antonio De Rose
Antonio De Rose
20,862 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
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
964 Points

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