Data Structures
Ruby Hashes
Working with Hashes
Ruby hashes store key-value pairs with symbol keys.
Introduction to Ruby Hashes
Ruby hashes are a fundamental data structure used to store collections of key-value pairs. In Ruby, hashes are particularly useful for managing data that is associated with unique identifiers, known as keys. Unlike arrays, which are indexed by integers, hashes allow you to use any object as a key, though symbols are most commonly used due to their efficiency.
Creating a Hash in Ruby
To create a hash in Ruby, you can use the { }
syntax or the Hash.new
method. The most common approach is to use literal syntax with symbols as keys.
Accessing Hash Values
Once a hash is created, you can access its values by referring to their keys. If a key does not exist, Ruby returns nil
. You can also provide a default value to be returned if a key is not found.
Modifying Hashes
Hashes in Ruby are mutable, which means you can add, change, or delete key-value pairs after the hash has been created.
Iterating Over Hashes
Ruby provides several ways to iterate over hashes, allowing you to perform operations on each key-value pair. The most common methods are each
, each_key
, and each_value
.
Common Hash Methods
Ruby hashes come with a variety of built-in methods for common operations. Here are a few useful ones:
keys
: Returns an array of all keys.values
: Returns an array of all values.has_key?
: Checks if a specific key exists.has_value?
: Checks if a specific value exists.