Symbol vs String
Symbols and strings look alike, but a symbol is a single unchangeable label while a string is editable text. Use symbols for names and strings for words that may change.
In this page:
Syntax
symbol = :name
string = "name"
symbol.object_id == :name.object_id # true
string.object_id == "name".object_id # false
Symbol vs String
Symbols (:name) are immutable and memory-efficient identifiers best used for things like hash keys, method names, and fixed sets of options, while strings ("name") are for actual text data that may change or be manipulated.
A common rule of thumb: if the value represents an identifier or category rather than user-facing text, a symbol is usually the better fit. Converting between them is easy with .to_sym and .to_s.
Note:
Rule of thumb: use a symbol for identifiers/categories (like :active), and a string for actual text data (like a person's name).
Example: Symbol vs String
status = :active # identifier -- symbol fits well
name = "Alice" # actual text data -- string fits well
puts status.to_s
puts name.to_sym.inspect
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using strings as hash keys where symbols are intended, so lookups return
nil. - Converting user text to a symbol with
to_symand expecting to modify it, when symbols are immutable. - Expecting
"a".object_idto be equal each time, when every string literal is a new object.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: