GGistDev

Symbols in Ruby

Lightweight, immutable identifiers; ideal as hash keys and labels.

Basics and interning

Symbols are interned (deduplicated); identical literals share the same object id.

:name.class    # => Symbol
:ok == :ok     # => true
:ok.object_id == :ok.object_id  # => true
"name".to_sym  # => :name
:status.to_s   # => "status"

Use cases

  • Hash keys, options, event types, or enum‑like values
  • Method names (reflection: :upcase, public_send(:upcase))
  • Case statements: cheap comparisons

Symbols vs strings

Use symbols for identifiers and options; strings for user data and text.

user = { name: "Matz", role: :admin }
user[:role] == :admin   # fast comparisons

Pitfalls

  • Do not generate unbounded new symbols from user input in older Rubies (symbols weren’t GC’d historically). Modern Ruby GC’s symbols but still avoid unbounded growth.

Conversion helpers

"field_name".to_sym
:field_name.to_s
%i[open closed archived]  # array of symbols

Summary

  • Immutable and interned; great for identity and keys
  • Prefer symbols for internal identifiers, strings for external/user data