What is Symbol in Ruby: Explanation and Examples
symbol is a lightweight, immutable identifier often used as names or keys. It is written with a colon prefix like :example and is more memory-efficient than strings for repeated use.How It Works
A symbol in Ruby is like a label or a name tag that you can attach to things in your code. Imagine you have a box and you want to mark it with a name. Instead of writing the full name every time, you use a simple tag that always means the same thing. This tag is the symbol.
Symbols are unique and stay the same throughout the program. When you write :name multiple times, Ruby uses the same symbol object each time, saving memory and making comparisons faster. Unlike strings, symbols cannot be changed once created, which makes them very efficient for identifiers.
Example
person = { :name => "Alice", :age => 30 }
puts person[:name]
puts person[:age]When to Use
Use symbols when you need a consistent, unchanging identifier, such as keys in hashes, method names, or constants. They are perfect when you want to label something without the overhead of strings.
For example, when defining options or settings, symbols make your code cleaner and faster. Avoid using symbols for user input or data that changes, as they are not meant to hold variable text.
Key Points
- Symbols are immutable and unique identifiers in Ruby.
- They are more memory-efficient than strings when reused.
- Commonly used as keys in hashes and method names.
- Cannot be changed once created.
- Use symbols for fixed labels, not for dynamic text.