Ruby Ruby Collections Ruby Hashes Working with Hash Keys

I don't see how it follows to set the "food" variable to true .

Can you help me figure this out?

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

Tagging Jay McGavren

There might be a problem with the tester on this one.

It only seems to be checking that the has_key? method has been called and that the food variable exists, not necessarily a true value.

3 Answers

Jacob Proffer
Jacob Proffer
24,584 Points

Hey Marguerite,

You can complete this challenge with a simple if statement. If the hash has the key "calories", declare a new variable called food and assign it the value of true:

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

This can also be simplified:

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

There might be a problem with this challenge.

Your simplification is going to set food to true regardless of whether the key exists or not because it's not part of an if statement.

You could do

food = true if hash.has_key?("calories")
Jacob Proffer
Jacob Proffer
24,584 Points

Hey Jason,

I just checked this out. That is interesting. Is there a way around it without an if?

Hey Jacob,

I don't know if there is anything that would match the instructions. Your first code example is pretty much what the instructions are guiding you to do.

We're not told what food should be if it doesn't have the key. It might be false or nil

Here's some other things you might be able to do, instead of an if, depending on what you want food to be if the key wasn't found.

if food should be set to true or false you could do

food = hash.has_key?("calories")

if food should be set to true or nil

# you could use the ternary operator but it's really a shortened version of an if/else
food = hash.has_key?("calories") ? true : nil

# or you could use the logical or operator
food = hash.has_key?("calories") || nil

These are probably not as straightforward as using an if

Is that what you were asking about or did I misunderstand?

I like both answers and was hard picking the best answer. Thx so much for your help.

Jay McGavren
STAFF
Jay McGavren
Treehouse Teacher

Hello Marguerite Holden and Jacob Proffer ,

Jason Anello is correct. This code should not have been able to pass the challenge:

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

hash.has_key?('calories')
  food = true

...But it did, because previously Treehouse only tested the code submission with a hash that did have a "calories" key. We did not test the submission with a hash that did not have a "calories" key to ensure the code still worked correctly.

I have fixed the tests for the challenge, which means the above code will no longer pass. The correct answers indicated elsewhere in this thread will still work, however.

Jacob Proffer
Jacob Proffer
24,584 Points

Hey Jay,

Thanks for the update.