Hashes help organize data by connecting keys to values, making it easy to find and use information quickly.
0
0
Why hashes are used everywhere in Ruby
Introduction
When you want to store a list of settings or options with names and values.
When you need to group related information about something, like a person's name and age.
When you want to look up data fast using a unique label instead of searching through a list.
When you want to pass many named arguments to a method clearly.
When you want to count or categorize items by their names.
Syntax
Ruby
hash = { key1: 'value1', key2: 'value2' }
# or
hash = { 'key1' => 'value1', 'key2' => 'value2' }Keys can be symbols (like :key1) or strings (like 'key1').
Values can be any type of data: numbers, strings, arrays, or even other hashes.
Examples
This hash stores a person's name and age using symbols as keys.
Ruby
person = { name: 'Alice', age: 30 }This hash uses strings as keys to store settings values.
Ruby
settings = { 'volume' => 10, 'brightness' => 70 }This creates a hash that starts counting from zero for any new key.
Ruby
counts = Hash.new(0) counts['apples'] += 1
Sample Program
This program creates a hash with information about a person and prints each detail by using the keys.
Ruby
person = { name: 'Bob', age: 25, city: 'New York' }
puts "Name: #{person[:name]}"
puts "Age: #{person[:age]}"
puts "City: #{person[:city]}"OutputSuccess
Important Notes
Hashes are very fast for looking up data by keys compared to searching arrays.
Using symbols as keys is common because they use less memory and are faster than strings.
You can store complex data by nesting hashes inside hashes.
Summary
Hashes connect keys to values to organize data clearly.
They are used everywhere in Ruby because they make data easy to find and manage.
Using hashes helps write clean and readable code when handling related information.