Data Structures
Crystal Hashes
Working with Hashes
Crystal hashes store key-value pairs with Hash type.
Introduction to Crystal Hashes
In Crystal, a hash is a collection of key-value pairs. It is an unordered, mutable data structure that allows you to store and retrieve values using unique keys. Hashes are particularly useful when you need to associate data, such as storing user information where the username is the key and the user details are the value.
Creating a Hash
You can create a hash in Crystal using the Hash
type. You define the types of keys and values within angle brackets. For example, a hash with String
keys and Int32
values would be defined as Hash(String, Int32)
.
Accessing and Modifying Hash Values
Hash values can be accessed using their keys. If you try to access a key that doesn't exist, it will return nil
unless a default value is set. You can modify existing entries by assigning new values to existing keys.
Setting Default Values
You can set a default value for a hash, which will be returned when accessing keys that do not exist. This can be done by passing the default value to the new
method or by using the default
method.
Iterating Over a Hash
Hashes can be iterated over using the each
method, which yields key-value pairs. This is useful for performing operations on each element in the hash.
Conclusion
Crystal hashes are powerful and flexible data structures for managing key-value pairs. They allow for efficient data retrieval and modification, making them essential for many programming tasks. With the ability to set default values and iterate over elements, hashes provide a robust solution for data management in Crystal.