Hashes

Back

Learning Goals

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

Vocabulary

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

Warm-Up

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

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 where 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 datatype:
    student1 = {
      "name" => "Christie Soto",
      "grades" => ["A+", "B", "in progress"],
      "active_student" => true
    }
    
  • Values can be accessed with bracket notation where we call the variable holding the hash and then bracket the key that corresponds to the data we’re wanting.
    • student1["name"] returns "Christie Soto"

Hash or Array?

For each example, determine if a Hash or Array would be more appropriate, and explain why.

  • 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:

:name   
:symbols_can_have_underscores
:"symbols can be in quotes"

You’ll learn more about Symbols in Mod 1, but for now, let’s see how a hash would look using Symbols as the keys 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. You can follow along by entering the following code into irb.

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

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

suitcase["jackets"]
#=> nil

We can create a new key-value pair:

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

We can remove the socks:

suitcase["socks"] = nil

or

suitcase.delete("socks")

Check on the shirts:

suitcase["shirts"]
#=> 3

Let’s check what keys are in our Hash:

suitcase.keys
#=> ["jeans", "shirts", "swimsuit"]

Let’s check what values are in our Hash:

suitcase.values
#=> [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. Add an animal to the zoo.
  4. Check how many hippos are in the zoo.
  5. Add another animal to the zoo.


Additional Practice

This additional practice is encouraged, but not required.

Complete the work in this repository.





Back