0
0
Rubyprogramming~3 mins

Why hashes are used everywhere in Ruby - The Real Reasons

Choose your learning style9 modes available
The Big Idea

Discover how a simple Ruby tool can save you from endless searching and mistakes!

The Scenario

Imagine you have a list of friends and their phone numbers written on paper. To find a number, you have to scan the whole list every time.

The Problem

This manual search is slow and frustrating. If the list grows, it takes longer to find a number. You might also make mistakes copying or reading the numbers.

The Solution

Hashes in Ruby act like a super-organized phone book. You give a friend's name (the key), and Ruby quickly finds the phone number (the value) without searching the whole list.

Before vs After
Before
friends = [['Alice', '123'], ['Bob', '456']]
number = nil
friends.each do |name, phone|
  if name == 'Bob'
    number = phone
  end
end
After
friends = { 'Alice' => '123', 'Bob' => '456' }
number = friends['Bob']
What It Enables

Hashes let you store and find data instantly by name, making your programs faster and easier to write.

Real Life Example

When a website remembers your settings, it uses hashes to quickly find your preferences without searching through all users.

Key Takeaways

Manual searching is slow and error-prone.

Hashes store data with keys for instant access.

This makes programs faster and simpler.