How to write with an error
#Error occurs if you use an invalid string as an identifier (starting with a number, including hyphens, spaces)
:5678 #=>SyntaxError
:rails-is-easy #=>Nameerror
:rails is easy #=>SyntaxError
:() #=>SyntaxError
#Effective as a symbol when surrounded by a single quote
:'5678' #=>"5678"
:'rails-is-easy' #=>"rails-is-easy"
:'rails is easy' #=>"rails is easy"
:'()' #=>"()"
Expression expansion in a symbol
#Use double quotes
title = 'Taro'
:"#{title.upcase}" #=> :TARO
Strings and symbols are different, so they are not compatible. However, there are methods that convert strings to symbols and methods that convert symbols to strings.
python
string = 'ruby'
sypbol = :ruby
string == symbol #=> false
#to_sym method:Convert strings to symbols
string.to_sym #=> :ruby
string.to_sym == symbol #=> true
#to_s method:Convert symbols to strings
symbol.to_s #=> "ruby"
symbol.to_s == string #=> true
References An introduction to Ruby for those who want to become professionals
Recommended Posts