Introduction to Ruby Hashes

Welcome to our exploration of data structures in Ruby! Today, we will delve into Ruby Hashes. Similar to a dictionary or an address book, hashes store data in key-value pairs, allowing for efficient data retrieval and modification. Hashes are essential in Ruby for managing and organizing data with unique identifiers. Let's dive into Ruby hashes to understand these concepts clearly.

Ruby Hashes

Ruby hashes are key-value collections that store data in pairs. They allow you to quickly access a value using its key. For example, a hash can store a friend's contact information, where their name (key) maps to their phone number (value).

contacts = {
  "Alice" => "123-456-7890",
  "Bob" => "234-567-8901"
}

puts contacts["Alice"]  # Output: "123-456-7890"
puts contacts["Carol"]  # Output: nil (key not found)

In this example, we create a simple hash with names as keys and phone numbers as values. Trying to access a nonexistent key, like "Carol," returns nil.

Operations with Hashes

Ruby hashes offer several operations for adding, updating, and accessing key-value pairs, making data management efficient.

Let's explore how each of these operations works one by one.

Adding or Updating Entries

You can add or update entries by assigning a value to a key. If the key exists, the value is updated; if it doesn’t, a new key-value pair is added.

contacts = {}
contacts["Alice"] = "123-456-7890"
contacts["Bob"] = "234-567-8901"
puts contacts.inspect  # Output: {"Alice"=>"123-456-7890", "Bob"=>"234-567-8901"}

This example demonstrates adding key-value pairs to a hash by directly assigning values.

Accessing Values with fetch

The fetch method retrieves the value associated with a key and lets you specify a default return value if the key doesn’t exist. This is useful to avoid exceptions when accessing keys that may not be present.

Ruby also provides the .key? method to check if a key exists in the hash. Using .key? can be helpful to verify a key’s presence before performing operations.

puts contacts.fetch("Alice", "Not found")  # Output: "123-456-7890"
puts contacts.fetch("Carol", "Not found")  # Output: "Not found"
puts contacts.key?("Alice")                # Output: true
puts contacts.key?("Carol")                # Output: false

The fetch method provides a fallback value, making it safer than direct key access, while .key? checks for the presence of a key and returns a boolean value.

Here are the key differences between fetch and direct access:

  • fetch Method:

    • Retrieves the value for a given key.
    • Allows specifying a default value if the key is not found.
    • Raises an error if the key is missing and no default is provided.
  • Direct Access or [] Method:

    • Retrieves the value for a given key.
    • Returns nil if the key is not found.
    • Does not provide a way to specify a default value directly.
Deleting Entries

To remove an entry, use the delete method with the key. This is useful for managing the hash’s contents.

contacts.delete("Bob")
puts contacts.inspect  # Output: {"Alice"=>"123-456-7890"}

The delete method removes the specified key-value pair from the hash.

Iterating Through Hashes

Ruby provides easy ways to loop through hashes using methods like each, each_key, and each_value. These methods let you iterate over keys, values, or key-value pairs.

tasks = { "Buy milk" => "Pending", "Pay bills" => "Completed" }

tasks.each do |task, status|
  puts "#{task}: #{status}"
end
# Output:
# Buy milk: Pending
# Pay bills: Completed

In this example, each iterates over the hash, providing access to both the key and value in each loop iteration.

You can also use each_key or each_value if you need only the keys or values:

tasks.each_key { |task| puts "Task: #{task}" }
# Output:
# Task: Buy milk
# Task: Pay bills
Nested Hashes

A hash in Ruby can contain other hashes, forming nested structures. This is useful for organizing complex data. For instance, a student record could contain a name as a key and a nested hash of subjects and grades as values.

class StudentDatabase
  def initialize
    @students = {}
  end

  def add_student(name, subjects)
    # Adds students and their subjects with grades
    @students[name] = subjects
  end

  def get_mark(name, subject)
    @students.fetch(name, {}).fetch(subject, "N/A")
  end

  def print_database
    # Prints each student's name along with their subjects and grades
    @students.each do |name, subjects|
      puts "Student: #{name}"
      subjects.each do |subject, grade|
        puts "  Subject: #{subject}, Grade: #{grade}"
      end
    end
  end
end

# Example usage
student_db = StudentDatabase.new
student_db.add_student("Alice", {"Math" => "A", "English" => "B"})
student_db.add_student("Bob", {"Math" => "C", "Science" => "B+"})

puts student_db.get_mark("Alice", "English") # Output: "B"
puts student_db.get_mark("Alice", "History") # Output: "N/A"
student_db.print_database
# Output:
# Student: Alice
#   Subject: Math, Grade: A
#   Subject: English, Grade: B
# Student: Bob
#   Subject: Math, Grade: C
#   Subject: Science, Grade: B+

This example demonstrates how to manage a nested hash structure within a class, where each student has their own record of subjects and grades.

Hash Defaults

You can set a default value for a hash to return when a key is not found. This avoids returning nil and can make your code more predictable.

inventory = Hash.new(0)
inventory["Apples"] += 10
inventory["Oranges"] += 5

puts inventory["Apples"]   # Output: 10
puts inventory["Bananas"]  # Output: 0 (default value)

In this example, the hash is initialized with a default value of 0, which is returned for keys that haven’t been added yet.

Practical Example: Managing a Shopping Cart

Let’s see a practical use of hashes by simulating a shopping cart. This hash-based cart stores product names as keys and quantities as values.

class ShoppingCart

  def initialize
    # Initialize cart as an empty hash
    @cart = Hash.new(0)
  end

  def add_product(product_name, quantity)
    # Add or update the quantity of a product in the cart
    @cart[product_name] += quantity
  end

  def remove_product(product_name)
    # Remove a product from the cart if it exists
    if @cart.key?(product_name)
      @cart.delete(product_name)
    else
      puts "#{product_name} is not in the cart."
    end
  end

  def show_cart
    # Display the products and their quantities in the cart
    if @cart.empty?
      puts "Your shopping cart is empty."
    else
      @cart.each { |product, quantity| puts "#{product}: #{quantity}" }
    end
  end
end

# Example usage
my_cart = ShoppingCart.new
my_cart.add_product("Apples", 5)
my_cart.add_product("Bananas", 2)
my_cart.add_product("Apples", 3)  # Updates quantity of Apples to 8

my_cart.show_cart
# Output:
# Apples: 8
# Bananas: 2

my_cart.remove_product("Bananas")
my_cart.show_cart
# Output:
# Apples: 8

In this example, we define a shopping cart system where product quantities are tracked as values in a hash. Using methods to add, remove, and display items, we demonstrate how a hash can efficiently manage a dynamic dataset like a shopping cart.

Lesson Summary and Practice

Great job! Today, we explored Ruby hashes, including how to create, access, and modify key-value pairs. We covered operations like adding, updating, deleting, and fetching values, as well as iterating over hash entries. We also examined nested hashes, hash defaults, and used fetch and .key? for safe access to values with a fallback or for checking key presence.

Practicing with hashes will deepen your understanding of Ruby data structures and prepare you for handling complex data sets. Experiment with creating, modifying, and nesting hashes to strengthen your skills!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal