Hashes

Store information in labeled pairs

7 min read

Arrays are great for lists, but sometimes you want to label your information instead of just numbering it. That is exactly what a hash is for. A hash stores information as pairs: a key, which acts like a label, and a value, which is the information attached to that label.

Creating a hash

You create a hash using curly braces, with each key connected to its value using => or the newer, shorter colon style.

person = { "name" => "Ava", "age" => 12 }
puts person

Here, "name" and "age" are the keys, and "Ava" and 12 are their matching values.

The modern symbol style

Most Ruby code today uses symbols as hash keys instead of plain strings, because symbols are a little faster and are the community standard. You will learn more about symbols later, but here is what they look like in a hash.

person = { name: "Ava", age: 12 }
puts person[:name]
puts person[:age]

This prints "Ava" and then 12. Notice the colon comes after the key name when you create the hash, but before the key name when you look up a value with square brackets.

Looking up and changing values

You can update a value or add a brand new key the same way you would with an array index.

person[:age] = 13
person[:city] = "Portland"

Hashes versus arrays

Use an array when order matters and items do not need labels, like a simple shopping list. Use a hash when you want to describe something with named details, like a person's name, age, and city all stored together.

A great way to think about a hash is like a small filing cabinet. Each key is a labeled drawer, and the value is whatever you keep inside that drawer.

Quick check

Q1 In a hash written as { name: "Ava", age: 12 }, what is name?

Q2 How do you look up the value for the key :age in a hash called person?

Want to save your progress? It's free.

Create a free account