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 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).
  • 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


Hash Syntax Practice

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

  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.

Take a screenshot or save in this work in a file and be ready to share it in Stand Up tomorrow!

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:

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. Print the value of the first animal of the zoo
  4. Add an animal to the zoo
  5. Check how many monkeys 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}"
end

#=> "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.





Back