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!

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

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,888 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.