Arrays and Hashes

25 Oct 2015
Like solar arrays and twitter tags? Not really...

So what are Arrays and Hashes? Well, they're both Ruby objects that we use to store multiple things. Imagine that you want a list of related items, like a catalogue of your favorite movies. You could store each one in its own string variable, adding a new variable whenever a new great movie comes out or you remember an old favorite. That's no good: it's messy, time consuming, and your code will be rife with unique variables. You should be using either an array or hash.

Let's continue with the example of our favorite movie catalogue; you really could use either array or hash depending on how you want to sort your movies. Arrays and hashes work in almost the same way except for one simple but crucial difference: an array assigns an index number to each of it's objects, starting with 0, but a hash requires you to specify a unique "key" for each object. Maybe all you need is a simple list: an array is the way to go, because all you want is the name of each movie. But maybe you want to be able to sort your movies by genre: then you want a hash.

Here's our example using some of my favorite movies:

An array might look like this if we "puts" each object:

While a hash would have more information for us:

You see, in the array, we just have a list: nice and simple. In the hash, we have a "key-value" relationship. The the "key" in a hash is like the index number in an array: each key is unique so that we can use it to refer to one and only one value in the hash. In our example, you'll see that I used the movie titles as keys and stored their genres in the values. Each movie title is unique, but the values can repeat; both "What We Do in the Shadows" and "Young Frankenstein" are comedies, for example.

There are many other reasons to use hashes or arrays, like storing usernames and passwords, and you'll find that in different situations one will be more useful than the other. Go out there and meddle with hashes and arrays, get a feel for how each one is best utilized.

Previous: Margins, Borders, and Padding | Next: An Enumerable method: cycle