Ruby Hashes

Hashes (sometimes known as associative arrays, maps, or dictionaries) are similar to arrays in that they are indexed collection of object references. However, while you index arrays with integers, you can index a hash with objects of any types: strings, regular expressions, and so on. When you store a value in a hash, you actually supply two objects - the index (normally called the key) and the value. You can subsequently retrieve the value by indexing the hash with the same key. The values in a hash can be objects of any type.

The example p040myhash.rb below, uses hash literals: a list of key => value pairs between braces.

The output is:

Compared with arrays, hashes have one significant advantage: they can use any object as an index.

Hashes have a default value. This value is returned when an attempt is made to access keys that do not exist in the hash. By default this value is nil.

The Hash class has many methods and you can refer them here.

Using Symbols as Hash Keys

Whenever you would otherwise use a quoted string, use a symbol instead. See the following example p041symbolhash.rb

Another example is p0411symbolhash.rb

The output is:

Another way (using name: value pairs to create a hash if the keys are symbols) of doing the same thing is as shown in p0412symbolhash.rb

The output is:

Exactly the same as in p0411symbolhash.rb

An exception to the shorter {symbol: value} syntax is when you would like to use a numeric key:

Note: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various Ruby Gurus), my acknowledgment and thanks to all of them. Much of the material on and in the course at is drawn primarily from the Programming Ruby book, available from The Pragmatic Bookshelf.