Array and Hash

Collections are at the heart of pretty much every program ever made. They allow us to harness the power of programming to do something many times, over many things, and so are always one of the first elements I seek to learn in a new language.


Arrays

Now that we know our basic type and a few operations to try out, lets put a bunch of Strings together in an Array collection.

 ❯ irb
2.4.1 :001 > names = ["Tom", "Sarah", "Sandy", "Rob", "Sarah"]
 => ["Tom", "Sarah", "Sandy", "Rob", "Sarah"]

Now lets explore some basic Array methods

2.4.1 :002 > names.first
 => "Tom"
2.4.1 :003 > names.last
 => "Sarah"
2.4.1 :004 > names.length
 => 5
2.4.1 :005 > names.uniq
 => ["Tom", "Sarah", "Tim", "Sandy", "Rob"]
2.4.1 :006 > names.uniq.length
 => 4

Hashes

The hash structure (also known as 'map' in other languages) is a key -> value collection used regularly in ruby. Consider the following

  • We have a collection of names
  • We also have a score for each name

To store these in Array is possible, but might not always be useful - what if we wanted to look up a person's score based on their name? Here's how it could happen with arrays:

2.4.1 :002 > names = ["Tom", "Sarah", "Dimitri"]
 => ["Tom", "Sarah", "Dimitri"]
2.4.1 :003 > scores = [1, 2, 3]
 => [1, 2, 3]

Here, we've stored all the scores in the same order as the names they relate to.

2.4.1 :004 >  names.find_index("Sarah")
 => 1
2.4.1 :005 > scores[1]
 => 2

So we could find the index of the name we're looking for, and then get the element at that index from the scores array.

But there's another way!

Hashes are initialised with the form {'key' => 'value'}

 ❯ irb
2.4.1 :001 > records = { "Tom" => 1, "Sarah" => 2, "Dimitri" => 3 }
 => {"Tom"=>1, "Sarah"=>2, "Dimitri"=>3}
2.4.1 :002 > records["Sarah"]
 => 2

Now we can just look up the name "Sarah" and get the score value back right away!

Have fun.

PS. The next post in the beginner series is here: Basic Ruby Blocks, which goes through how to iterate through a basic collection.