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,129 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".