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 Ruby Hash Creation

Breaking down the parts of a Hash

{"name" => "Bread"}

Ok so the video never really explicitly said what each component does in creating a part of a hash...so I assume that the string on the left is the key and the equals and chevron are the symbols that create the item in the hash that relates to the key...but can someone confirm this? Are there ever exceptions? Also, what would happen if you just used an equals sign vs. the chevron too?

{"name" = "Bread"}

1 Answer

Stephen Beckstrand
Stephen Beckstrand
11,169 Points

Hey nekilof, as you continue throughout the courses, more information is provided, but you are correct. On the left, you have your "key", and on the right, you have a value assigned to that key within the hash.

First off, '=>' is used to assign a value to a key, just using '=' will result in a syntax error.

As far as exceptions go, you dont have to limit yourself in terms of what values can be assigned to a key in a hash. For instance, the value does not have to be a string, it can also be an integer, or an array, etc. One useful function of a hash might be to have multiple values assigned to one key via an array, such as:

hash = { "states" => ["New York", "Arizona", "Colorado"], "capitals" = ["Albany", "Phoenix", "Denver"]}

That way one key can store a value with more diverse information that can be called later. In this case, the key "states" has a "value" of an array with multiple objects. Same with the capitals "key".