Introduction

Hashes, also known as dictionaries or associative arrays in other programming languages, are a fundamental data structure in Ruby. They store data in key-value pairs, allowing for efficient data retrieval based on unique keys.

Key Concepts

  • Key-Value Pairs: Each element in a hash is a pair consisting of a unique key and a corresponding value.
  • Unique Keys: Keys in a hash must be unique, but values can be duplicated.
  • Mutable: Hashes can be modified after creation, allowing for dynamic data manipulation.

Creating a Hash

You can create a hash using the Hash class or the literal syntax.

Using the Hash Class

# Creating an empty hash
my_hash = Hash.new

# Creating a hash with default values
default_hash = Hash.new("default value")

Using Literal Syntax

# Creating an empty hash
my_hash = {}

# Creating a hash with initial key-value pairs
person = { "name" => "Alice", "age" => 30, "city" => "New York" }

Accessing and Modifying Hashes

Accessing Values

You can access values in a hash using their keys.

person = { "name" => "Alice", "age" => 30, "city" => "New York" }
puts person["name"]  # Output: Alice
puts person["age"]   # Output: 30

Modifying Values

You can modify existing values or add new key-value pairs.

person["age"] = 31  # Modifying an existing value
person["country"] = "USA"  # Adding a new key-value pair

Deleting Key-Value Pairs

You can delete key-value pairs using the delete method.

person.delete("city")

Iterating Over Hashes

You can iterate over hashes using various methods like each, each_key, and each_value.

Using each

person.each do |key, value|
  puts "#{key}: #{value}"
end

Using each_key and each_value

person.each_key do |key|
  puts key
end

person.each_value do |value|
  puts value
end

Common Hash Methods

Here are some commonly used methods for working with hashes:

Method Description
keys Returns an array of all keys in the hash
values Returns an array of all values in the hash
has_key?(key) Checks if the hash contains the specified key
has_value?(value) Checks if the hash contains the specified value
merge(other_hash) Combines two hashes, returning a new hash

Example

person = { "name" => "Alice", "age" => 30, "city" => "New York" }

# Getting all keys
puts person.keys  # Output: ["name", "age", "city"]

# Getting all values
puts person.values  # Output: ["Alice", 30, "New York"]

# Checking for a key
puts person.has_key?("name")  # Output: true

# Checking for a value
puts person.has_value?("Alice")  # Output: true

# Merging two hashes
additional_info = { "country" => "USA", "occupation" => "Engineer" }
merged_person = person.merge(additional_info)
puts merged_person
# Output: {"name"=>"Alice", "age"=>30, "city"=>"New York", "country"=>"USA", "occupation"=>"Engineer"}

Practical Exercises

Exercise 1: Creating and Accessing a Hash

Create a hash representing a book with keys: title, author, year, and genre. Access and print each value.

Solution

book = { "title" => "1984", "author" => "George Orwell", "year" => 1949, "genre" => "Dystopian" }
puts book["title"]   # Output: 1984
puts book["author"]  # Output: George Orwell
puts book["year"]    # Output: 1949
puts book["genre"]   # Output: Dystopian

Exercise 2: Modifying a Hash

Add a new key-value pair publisher to the book hash and modify the year to 1950.

Solution

book["publisher"] = "Secker & Warburg"
book["year"] = 1950
puts book
# Output: {"title"=>"1984", "author"=>"George Orwell", "year"=>1950, "genre"=>"Dystopian", "publisher"=>"Secker & Warburg"}

Exercise 3: Iterating Over a Hash

Iterate over the book hash and print each key-value pair in the format key: value.

Solution

book.each do |key, value|
  puts "#{key}: #{value}"
end
# Output:
# title: 1984
# author: George Orwell
# year: 1950
# genre: Dystopian
# publisher: Secker & Warburg

Conclusion

Hashes are a versatile and powerful data structure in Ruby, allowing for efficient storage and retrieval of data using key-value pairs. Understanding how to create, access, modify, and iterate over hashes is essential for effective Ruby programming. In the next section, we will explore iterators, which provide additional ways to traverse and manipulate collections in Ruby.

© Copyright 2024. All rights reserved