What is a symbol in Ruby and when do I use one?
Short answer
A symbol like :name is an immutable, interned identifier. Use symbols for hash keys, method names and option flags; use strings for text a user will read or edit.
:name.class # Symbol
"name".class # String
:name.object_id == :name.object_id # true — the same object every time
"name".object_id == "name".object_id # false — two separate stringsEvery occurrence of :name in your program is the same object in memory. That makes symbol comparison a pointer check rather than a character-by-character one, which is why hashes use them.
#The rule of thumb
Symbol when it names something: hash keys, method names, states, option flags.
video = { title: "Intro to Ruby", track: :ruby, level: :beginner }
send(:upcase)
attr_accessor :nameString when it is content: anything displayed, stored, concatenated or edited.
#The modern hash syntax
{ title: "Intro" } # symbol keys — the common form
{ :title => "Intro" } # identical, older syntax
{ "title" => "Intro" } # string keys — different keys entirelyhash[:title] and hash["title"] are not interchangeable. Mixing them is a frequent source of nil where you expected a value.
#Converting
:ruby.to_s # "ruby"
"ruby".to_sym # :ruby