Ruby Hashes

Store and retrieve data using key-value pairs

🗂️ What are Ruby Hashes?

Hashes are collections of key-value pairs, similar to dictionaries. They allow you to store and access data using unique keys instead of numeric indexes, making data retrieval fast and intuitive.


# Creating a simple hash
person = { "name" => "Alice", "age" => 25 }
puts person["name"]  # Output: Alice
                                    

Output:

Alice

Hash Basics

📝

Creating Hashes

Multiple ways to create hashes

# Using hash rocket
user = { "name" => "Bob" }

# Using symbols
user = { name: "Bob" }
🔍

Accessing Values

Retrieve data using keys

person = { name: "Alice" }
puts person[:name]

Adding Items

Insert new key-value pairs

person = {}
person[:age] = 30
🔄

Updating Values

Modify existing values

person[:age] = 31
puts person[:age]

🔹 Creating Hashes

Hashes store data as key-value pairs. You can create them using hash rockets (=>) or symbol notation. Hash rockets work with any key type, while symbol notation is cleaner for symbol keys and commonly used in modern Ruby code.

# Empty hash
empty_hash = {}

# Hash with string keys
student = { "name" => "John", "grade" => "A", "age" => 20 }

# Hash with symbol keys (modern syntax)
student = { name: "John", grade: "A", age: 20 }

# Using Hash.new
scores = Hash.new
scores["math"] = 95

puts student[:name]   # Output: John
puts scores["math"]   # Output: 95
                            

Output:

John

95

🔹 Accessing Hash Values

Access hash values using square brackets with the key. If a key doesn't exist, Ruby returns nil by default. You can also use the fetch method for safer access with custom default values or error handling.

person = { name: "Alice", age: 25, city: "New York" }

# Accessing values
puts person[:name]        # Output: Alice
puts person[:age]         # Output: 25

# Non-existent key returns nil
puts person[:country]     # Output: (nothing)

# Using fetch with default value
puts person.fetch(:country, "USA")  # Output: USA

# Check if key exists
puts person.key?(:name)   # Output: true
                            

Output:

Alice

25

USA

true

🔹 Modifying Hashes

Hashes are mutable, meaning you can add, update, or delete key-value pairs after creation. Use square brackets to add or update values, and the delete method to remove entries. This flexibility makes hashes perfect for dynamic data storage.

book = { title: "Ruby Guide", pages: 200 }

# Adding new key-value pair
book[:author] = "Jane Doe"

# Updating existing value
book[:pages] = 250

# Deleting a key-value pair
book.delete(:pages)

puts book  # Output: {:title=>"Ruby Guide", :author=>"Jane Doe"}
                            

Output:

{:title=>"Ruby Guide", :author=>"Jane Doe"}

🔹 Iterating Through Hashes

Loop through hashes using the each method to access both keys and values. You can also iterate over just keys or just values using the keys and values methods. This is useful for processing or displaying hash data.

fruits = { apple: 3, banana: 5, orange: 2 }

# Iterate through key-value pairs
fruits.each do |fruit, count|
  puts "#{fruit}: #{count}"
end

# Iterate through keys only
fruits.keys.each do |fruit|
  puts fruit
end

# Iterate through values only
fruits.values.each do |count|
  puts count
end
                            

Output:

apple: 3

banana: 5

orange: 2

🔹 Common Hash Methods

Ruby provides many built-in methods for working with hashes. These methods help you check hash properties, merge hashes together, get all keys or values, and more. Learning these methods makes hash manipulation easier and more efficient.

data = { a: 1, b: 2, c: 3 }

# Get all keys
puts data.keys.inspect       # Output: [:a, :b, :c]

# Get all values
puts data.values.inspect     # Output: [1, 2, 3]

# Check if empty
puts data.empty?             # Output: false

# Get size
puts data.size               # Output: 3

# Merge two hashes
more_data = { d: 4, e: 5 }
combined = data.merge(more_data)
puts combined.inspect        # Output: {:a=>1, :b=>2, :c=>3, :d=>4, :e=>5}
                            

Output:

[:a, :b, :c]

[1, 2, 3]

false

3

{:a=>1, :b=>2, :c=>3, :d=>4, :e=>5}

🧠 Test Your Knowledge

How do you access a value in a hash with symbol key :name?