What is the difference between symbols and strings in Ruby, and why does Rails prefer symbols for hash keys?

Beginner

Answer

Symbols are immutable and stored in memory only once, while strings create new objects each time. Rails prefers symbols because:

  • Memory efficiency - symbols are stored once
  • Performance - faster comparison operations
  • Immutability - prevents accidental modification
# Symbol - same object_id
:name.object_id == :name.object_id  # true

# String - different objects
"name".object_id == "name".object_id  # false