0
0
Rubyprogramming~5 mins

Symbol type and immutability in Ruby

Choose your learning style9 modes available
Introduction

Symbols are simple names used to represent things in Ruby. They are fast and never change, which helps your program run better.

When you need a label or name that stays the same throughout your program.
When you want to use keys in a hash that do not change.
When you want to save memory by reusing the same name instead of creating new strings.
When you want to compare names quickly without extra work.
Syntax
Ruby
:symbol_name

Symbols start with a colon : followed by letters, numbers, or underscores.

They are immutable, meaning once created, they cannot be changed.

Examples
A simple symbol representing the word 'name'.
Ruby
:name
A symbol with an underscore, often used as a key in hashes.
Ruby
:user_id
A symbol that includes numbers and underscores.
Ruby
:age_30
Sample Program

This program shows that two symbols with the same name are equal and share the same object ID, proving symbols are unique and immutable.

Ruby
name1 = :ruby
name2 = :ruby

puts name1 == name2
puts name1.object_id == name2.object_id
OutputSuccess
Important Notes

Symbols are not strings. They are more like labels or names.

Because symbols never change, Ruby stores only one copy of each symbol, saving memory.

Be careful not to create symbols from user input repeatedly, as symbols are not garbage collected in some Ruby versions.

Summary

Symbols are names that never change and are written with a colon :.

They are useful for keys and labels because they are fast and use less memory.

Two symbols with the same name are always the same object.