Mike's Blog

Best Friends: Arrays and Hashes

A quick guide to differences between Arrays and Hashes

September 8th 2015

What happens if we want to work with many pieces of data in ruby? A collection? A series of numbers that we need to put in ascending order? Or a list of names sorted alphabetically? How does Ruby manage that? Ruby gives us two tools: hashes and arrays. Which one should we use? We will dive in to both in this post!


Array

The official Ruby documentation definition of arrays, you’ll see that an array is defined as an ordered, integer-indexed collection of objects. What a mouthfull! Lets examine.


Hash

A Hash is a collection of key-value pairs like this: "first_name" => "Mike". It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index.


The Differences Between Arrays and Hashes

Hashes and Arrays have some key differences:

  1. Hash keys are not integer keys. They can be characters, integers, strings, etc. — basically, any Ruby object type. Array indexes are integers only.
  2. The hash keys are not ordered. So, you couldn’t say that a is “first” or that it “comes before”, because Ruby does not look at the order of keys in hashes.
  3. Even though hash keys are not ordered, if you were iterating through a hash Ruby would go through them in the order in which they were added to the hash.