What is Hash in Ruby: Explanation and Examples
Hash is a collection of key-value pairs, similar to a real-life dictionary where you look up a word (key) to find its meaning (value). It allows you to store and access data by keys instead of just by position like in arrays.How It Works
A Hash in Ruby works like a labeled box where each label (called a key) points to a specific item (called a value). Imagine you have a box with compartments labeled 'name', 'age', and 'city'. You can quickly find the item in the 'name' compartment without searching through the whole box.
Ruby hashes let you store data this way, so you can access values directly by their keys. Keys can be many types like strings or symbols, and each key is unique in the hash. This makes hashes very useful for organizing data where you want to find things by name or label instead of by order.
Example
This example shows how to create a hash, add key-value pairs, and access a value by its key.
person = { name: "Alice", age: 30, city: "New York" }
puts person[:name]
puts person[:age]
puts person[:city]When to Use
Use a Hash when you need to store related information that you want to access by a meaningful label instead of a number. For example, storing user details, configuration settings, or any data where keys describe what the values mean.
Hashes are great for fast lookups, like finding a phone number by a person's name or settings by their option name. They help keep your data organized and easy to read.
Key Points
- A
Hashstores data as key-value pairs. - Keys are unique and can be symbols, strings, or other objects.
- You access values by their keys, not by position.
- Hashes are useful for organizing and quickly finding data.