Learning Goals

  • Use Ruby syntax to declare variables that store Hashes
  • Access data from Ruby Hashes
  • Iterate over Hashes with each


  • Hash
  • hash rocket
  • key
  • key-value pair
  • value


Look at the following array and take a moment to consider: What is problematic about it? How would you prefer to structure a list of students and such information?

students = ["Cristie Soto", "A+", "B", "in progress", true, "Oscar Smith", "A-", "D", "dropped", true]


Hashes allow us to structure data in a different way than Arrays. It’s not better; it’s just different. Like an Array, a Hash is a data structure used for representing a collection of things. But whereas an Array generally represents a list of ordered, indexed values, a Hash represents a collection of named values. These names are called keys, and each key has a corresponding value. In a Hash, we can insert data by assigning it to a name and later retrieving it using the same name.

Some languages call their Hashes dictionaries for this reason – you look up a word (the label) to retrieve its definition (the data or value with which the label was associated).

Hash Syntax

  • A hash is enclosed in curly braces { }, key-value pairs are separated by commas, and keys and values are separated by either a hash rocket (=>) (or a colon if the key is a symbol).
  • Each key in a hash must be unique
    • If you attempt to have duplicate keys when you first create a hash, you will get a warning: key :key_name is duplicated and overwritten on line X error
    • If you try to add a new key-value pair using a key that already exists, that new key-value pair will overwrite the previous one - dangerous.
  • Keys and values can be any type of object:
    student1 = {
      "name" => "Christie Soto",
      "grades" => ["A+", "B", "in progress"],
      "active_student" => true
  • Values can be accessed with bracket notation:
    • student1["name"] returns "Christie Soto"

Hash or Array?

For each example, determine if a Hash or Array would be more appropriate, and explain why. Share your responses in the Slack small group channel for feedback and discussions.

  • A store's inventory
  • The contents of a dishwasher
  • List of all the places you've traveled to
  • List of birthdays of all students
  • Names of all dogs at doggie daycare
  • Virtual address book
  • Items of clothing in a dresser

Symbols as Keys

In Ruby, symbols are basically Strings that can’t change. You can recognize a symbol because it starts with a colon :. All of the following are symbols:

:"symbols can be in quotes"

Symbols are also faster than strings because Ruby can determine if two symbols are equal by checking their object_id. Strings have to be compared character by character.

So if symbols are faster and more efficient than strings, why would we use strings? A string’s value can change, making them useful as variables. Strings are mutable, whereas symbols are immutable.

Let’s recreate our student1 hash using symbols instead of strings.

student1 = {
    :name => "Christie Soto",
    :grades => ["A+", "B", "in progress"],
    :active_student => true

Since it’s quite common to use symbols as keys in hashes, Ruby gives us a handy shortcut for creating a hash with symbol keys:

student1 = {
    name: "Christie Soto",
    grades: ["A+", "B", "in progress"],
    active_student: true

These two definitions for our student1 hash produce the exact same hash, however the second is the preferred syntax. Please note: The colon must immediately follow the name of the key without any spaces in between.

Hash Syntax Practice

Complete the following work in an irb session or a new Ruby file, working in VS Code:

  1. For one of the examples in the previous activity that you selected would be best suited for a Hash, declare a variable that stores a Hash with some (possibly fake) data.
  2. Declare a variable that stores a Hash that represents this tweet.

Accessing a Hash

We use bracket notation ([]) to access values stored in a Hash just like Arrays, only we don’t reference the index position, we instead reference keys.

The examples below explore the suitcase Hash:

suitcase = { 
  "socks" => 4, 
  "jeans" => 1

Did we put any jackets on our list? Let’s check:

#=> nil

We can create a new key-value pair:

suitcase["shirts"] = 3
suitcase["swimsuit"] = true

We can remove the socks:

suitcase["socks"] = nil



Check on the shirts:

#=> 3

Let’s check what keys are in our Hash:

#=> ["jeans", "shirts", "swimsuit"]

Let’s check what values are in our Hash:

#=> [1, 3, true]

Note that when we use the .keys and .values Hash methods, the return value of each is an Array!

Hash Syntax and Access Practice

Use the following zoo variable to complete each prompt:

  zoo = {
    giraffes: 3,
    zebras: 12,
    hippos: 2
  1. Print all of the keys of the zoo Hash.
  2. Print all of the values of the zoo Hash.
  3. Print the value of the first animal of the zoo.
  4. Add an animal to the zoo.
  5. Check how many hippos are in the zoo.
  6. Add another animal to the zoo.
  7. Print all of the keys of the zoo Hash.

Iterating over Hashes

Oftentimes, we will want to iterate over a Hash to do something with each key-value pair. This works a lot like iterating over an Array, with one small exception. Take a look at the code snippet below and see if you can identify the difference between iterating over a Hash vs over an Array:

suitcase = { 
  "socks" => 4, 
  "shirts" => 2

#=> {"socks" => 4, "shirts" => 2}

suitcase.each do |clothing_item, quantity|
	p "I need #{quantity} #{clothing_item}"

#=> "I need 4 socks"
#=> "I need 2 shirts"

Now, instead of having one block variable to work with, we have two. The first represents the key, and the second represents the value.

Check For Understanding

Complete the work in the CFU repository and submit your work using the submission form.