9. Hashes

In this lesson, we are going to learn about hashmaps (otherwise called a "hash").

Hashes are just another way to store data, just like arrays. The main difference is that we can access elements without using indexes (array[0]).

For example, in an array, you can store a list of items and access them using numbers:

food = ["Pizza", "Pasta", "Noodles", "Rice", "Vegetable"]

puts food[1]
=> "Pasta"

puts food[4]
=> "Vegetable"

food[4] = "Sushi"

puts food[4]
=> "Sushi"

The important thing to note is that in arrays, we access elements using numbers or in otherwords, the index.

With hashes, you can access the elements using anything. For example, here is a hash representing people's name and age:

people = {
"Jake" => 30,
"Adam" => 31,
"Mike" => 25
}

puts people["Jake"]
=> 30

puts people["Mike"]
=> 25

people["Mike"] = 27

puts people["Mike"]
=> 27

As you can see, we aren't using numbers to access elements, we're using strings to access them.

It's not limited to strings - we can use any data type you want:

things = {
1 => "This is one",
10.0 => "This is a float",
true => "Booleans work too?!"
}

puts things[1]
=> "This is one"

puts things[10.0]
=> "This is a float"

puts things[true]
=> "Booleans work too?!"

We call the element that we use to access an element a key, and the element being accessed a value.

hash = {
"this side is the key" => "this side is the value"
}

We call a pair of keys and values a key value pair.

In the people hash above, "Jake" is the key, and 30 is the value. "Jake" and 30 are paired, thus they are called key value pairs.

Next, "Adam" is the key, and 31 is the value. Again, "Adam" and 31 are a key value pair.


Overview

As we have seen above, hashes can be created with the {} syntax.

An empty hash can be created with {} or Hash.new:

new_hash = {}

another_new_hash = Hash.new

Let's go back to our people hash:

people = {
"Jake" => 30,
"Adam" => 31,
"Mike" => 25
}

Let's say we want to get the age of "Jake". We can simply write the following code:

people["Jake"]
=> 30

As you can see, with hashes, we give it the key and we get the value.

We can also replace the value of a key easily:

# We give it the key and we get the value
people["Jake"]
=> 30

# We can assign the value of the key to something else
people["Jake"] = 100

# Now the value is 100 (it used to be 30)
people["Jake"]
=> 100

We can also add to a value like this:

people["Jake"]
=> 100

people["Jake"] += 5

people["Jake"]
=> 105

+=, -=, *=, /=

When programming, you will see +=, -=, *=, / being used quite a lot. They are self-explanatory - take a look at the examples below:

number = 5

# 5 + 5
number += 5

number
=> 10

# 10 - 2
number -= 2

number
=> 8

# 8 * 5
number *= 5

number
=> 40

# 40 / 10
number /= 10

number
=> 10

We are basically taking the existing value of the variable and performing mathematical operations on them. For example:

number = 5

# This is the same as
number *= 10

# this
5 * 10

We can add a new item to our existing hash as such:

people["Bob"] = 21

people
=> {"Jake"=>100, "Adam"=>31, "Mike"=>25, "Bob"=>21}

In a nutshell, how are hashes useful?

Hashes are like a dictionary. In fact, dictionaries can be somewhat represented by hashes.

dictionary = {
  "a" => {
    "ape" => "a large primate that lacks a tail, including the gorilla, chimpanzees, orang-utan, and gibbons.",
    "apple" => "the round fruit of a tree of the rose family, which typically has thin green or red skin and crisp flesh.",
    ...etc...
  },
  "b" => {
    "banana" => "a long curved fruit which grows in clusters and has soft pulpy flesh and yellow skin when ripe.",
    ...etc...
  }
}

dictionary["a"]["ape"]
=> a large primate that lacks a tail, including the gorilla, chimpanzees, orang-utan, and gibbons.

When you find a word in a dictionary (no Google), this is what you would do:

Let's look at the example of the hash representing a dictionary that we created above:

Notice the similarity?

What is the difference between an array and a hash?

An array is an ordered list of items which allow you to access elements using indexes. A hash allows you store data and access them using the key.

When to use a hash?

When you have to take a value and look up another value based on it (taking "ape" and looking up the definition for it).

When to use an array?

When you want to store things that need to be ordered, and you only need to be able to look them up by a numeric index.

Assignment