Arrays, Hashes, what are all of these Ruby collection and container objects?

A Week 3 Reflection

April 26, 2015

Let's start out by describing what an 'array' is versus a 'hash.' Arrays are an ordered collection of objects. David Black, in "The Well-Grounded Rubyist" notes that you "can select objects from the collection based on a consistent, consecutive numerical index."

For example, we could have an array that includes the meals in a day:

meals = ["breakfast", "lunch", "dinner"]

The array because the array tracks the order of the items, we know that breakfast is the first object, lunch is the second, and dinner is the third. If we wanted to call the second item in the meals array, we could call it by writing meals[0]. The first item in the array is always called via a 0. The next item is a 1, so meals[1] would return lunch.

In contrast, hashes do not necessarily have to be ordered. In fact, it was not possible to order a hash until more recent releases of Ruby. Hashes store objects in pairs, where each pair has a key and a value. Whereas, the ingredients in a fruit salad could be a hash. Each ingredient has it's own "size/amount" that needs to go in the salad, but it doesn't matter which order the items are assembled. Take for instance the following hash:

tasty_fruit_salad = { "10" => "strawberries", "40" => "blueberries", "2" => apples}

The great benefit of a hash is that I don't need to remember which "order" the apples are in. I can find the number of apples I need by calling apples in the hash: tasty_fruit_salad[apples] which will return 2.

Arrays and hashes are both powerful ways to store and manage data, and each has their own particular use cases.