Hash
Hashes associate a key to some value. You may then retrieve the value based upon its key. Hashes can map from anything to anything! You can map from Strings to Numbers, Strings to Strings, Numbers to Boolean's… and you can mix all of those. Symbols are especially common as keys. Symbols look like this :symbol. A symbol is a colon followed by some characters. You can think of them as special strings that stand for (symbolize) something! We often use symbols because Ruby runs faster when we use symbols instead of strings.
Create Hash
You create a hash by surrounding the key-value pairs with curly braces. The arrow always goes from the key to the value depicting the meaning: "This key points to this value.". Key-value pairs are then separated by commas.
Accessing a Hash
Accessing an entry in a hash looks a lot like accessing it in an array. However with a hash the key can be anything, not just numbers. If you try to access a key that does not exist, the value nil is returned, which is Ruby's way of saying "nothing", because if it doesn't recognize the key it can't return a value for it.
Assigning Values to a Hash
Assigning values to a hash is similar to assigning values to an array. With a hash, the key can be a number or it can be a symbol, string, number... or anything.
Most common hash methods
Last updated