← Back to Ruby Course | Chapter 12: Ruby Best Practices | Lesson 3 of 6

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:

  1. Symbol vs String
Syntax
ruby
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

markup
status = :active     # identifier -- symbol fits well
name = "Alice"       # actual text data -- string fits well

puts status.to_s
puts name.to_sym.inspect
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
  1. Using strings as hash keys where symbols are intended, so lookups return nil.
  2. Converting user text to a symbol with to_sym and expecting to modify it, when symbols are immutable.
  3. Expecting "a".object_id to 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.