Ruby Ruby Collections Ruby Hashes Working with Hash Keys

Alphonse Cuccurullo
Alphonse Cuccurullo
2,513 Points

Using the has_key? method, check if the hash variable has a key called "calories". If it does, set a new variable called

So aside from helping me out with this question. Im super lost.....Like he only demonstraighted this using the console as opposed to the text editor. An another thing is that im trying to see the purpose of hash keys. Will there ever be a situation where i can use them? are they neccessary or more in demand then arrays?

1 Answer

Tim Knight
Tim Knight
28,862 Points

First you could solve the problem with something like this:

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

Hashes are pretty common actually. If I recall, if you're coding in Rails... an ActiveRecord query is an array of hashes.