0
0
Rubyprogramming~3 mins

Why Symbol type and immutability in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your program could remember names just once and never get confused by changes?

The Scenario

Imagine you have a list of names you use repeatedly in your program, like keys for a dictionary. You write each name as a string every time you need it.

The Problem

Writing the same string over and over wastes memory and slows your program. Also, strings can be changed by mistake, causing bugs that are hard to find.

The Solution

Symbols are like names that never change and are stored only once. Using symbols saves memory and makes your program faster and safer.

Before vs After
Before
hash = { 'name' => 'Alice', 'age' => 30 }
puts hash['name']
After
hash = { name: 'Alice', age: 30 }
puts hash[:name]
What It Enables

Using symbols lets your program run faster and use less memory by reusing the same unchangeable names everywhere.

Real Life Example

When building a website, you often use keys like :title or :author many times. Symbols keep these keys efficient and safe throughout your code.

Key Takeaways

Symbols are unique, unchangeable names stored once in memory.

They save memory and speed up your program compared to repeated strings.

Symbols help avoid bugs by being immutable (unchangeable).