Arrays and Hashes in Ruby

November 12, 2014

Instead of working with one object, many times one wants to work with many objects–a collection of objects. Ruby represents collections of objects by putting them inside container objects. Two popular container objects are the array and the hash.

An array is an ordered collection of objects. The objects are indexed numerically, starting from 0 and increasing by 1 as new objects are added to the array. In this way, an array acts as a list, starting the count at 0. Objects in the array can be accessed using the numerical index. The objects always stay in the same order unless one explicitly moves them around.

A hash is also an ordered collection of objects. However, the objects are stored in pairs. Each pair consists of a key and a value, which can be any Ruby object (like a string). The values in the hash can be accessed using the keys. In this way, hashes act like lists, but instead of being numbered, each list item is prefixed with a unique key. There can be only one value for any given key. Hashes also remember the order in which key/value pairs were entered.

Clearly, arrays and hashes are very similar. An array could be considered a hash, just with consecutive numbers representing the keys. And a hash could be considered an array, where the index can be anything, not just consecutive numbers. Arrays act as the staple of lists and collections. Hashes act as a more specialied list, allowing one to lookup values more easily.