Symbols

View saved

What a symbol is

A symbol starts with a colon. It represents a name, not mutable text.

status = :loading
puts status
puts status == :loading

Symbols as hash keys

The shortcut name: creates a symbol key.

course = { title: "Ruby", level: :beginner }
puts course[:level]

Convert when needed

Move between strings and symbols deliberately.

puts :title.to_s
puts "title".to_sym

When to use symbols

  • Use symbols for fixed identifiers and options
  • Use strings for free-form text and input
  • Comparing symbols is fast and common in APIs
  • Do not convert huge sets of user input into symbols carelessly

Comments

One comment per signed-in account. Comments are saved with this page’s URL.