What are symbols in Ruby?
In Ruby, a symbol is a lightweight, immutable object used to represent names, keys, or identifiers.
A symbol always starts with a colon, like :name or :age.
A symbol is like a label — it represents something, but is not meant to change.
Symbols vs Strings
At first glance, symbols look like strings, but they behave very differently.
- 🔤 String: mutable, used for text data
- 🏷️ Symbol: immutable, used as identifiers
name1 = "hello" # string name2 = :hello # symbol
Why use symbols?
- 🚀 Faster comparison than strings
- 💾 Lower memory usage (only stored once)
- 📌 Ideal for keys and identifiers
- ⚙️ Common in Ruby internals and frameworks
Symbols in Hashes
Symbols are most commonly used as keys in hashes.
user = { :name => "Alice", :age => 25 }
Modern Ruby also allows a shorter syntax:
user = { name: "Alice", age: 25 }
Are symbols mutable?
No. Symbols are immutable, meaning they cannot be changed after creation. This makes them safe for reuse across your program.
How symbols work internally
Ruby stores each symbol only once in memory. That means every use of :name points to the same object.
Why symbols matter
- 🛡️ Efficient memory usage
- ⚙️ Faster performance in comparisons
- 📦 Clean and readable code in hashes and APIs
- 👥 Widely used in frameworks like Rails
Ruby on Rails heavily uses symbols for route names, parameters, and configuration keys.
Summary
Symbols in Ruby are immutable identifiers used to represent names efficiently. They are faster and more memory-friendly than strings and are commonly used as keys in hashes.
In short: Symbols are reusable labels, not editable text.