[RUBY] What you learned about symbols

Precautions for creating symbols

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

Symbols and strings

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

What you learned about symbols
What you learned about hashes
What I learned about Kotlin
About Ruby symbols
Take what you've learned about Java reflection
What i learned
About Ruby Symbols
[Rails Struggle/Rails Tutorial] What you learned in Rails Tutorial Chapter 6
Summary of what I learned about Spring Boot
[Rails Struggle/Rails Tutorial] What you learned in Rails Tutorial Chapter 3
What I learned ① ~ DJUnit ~
I will write what I learned about docker anyway (second)
[Rails Struggle/Rails Tutorial] What you learned in Rails Tutorial Chapters 4 and 5
I will write what I learned about docker anyway (first)
What I researched about Java 6
What I researched about Java 9
About Ruby hashes and symbols
What I researched about Java 7
Summarize the words you learned
config.ru What are you doing?
What you learned when you acquired Java SE 8 Silver and Gold
[Android / Java] Learned about DataBinding
What I researched about Java 5
What I learned from studying Rails
About the language to be learned
[Super Introduction] About Symbols in Ruby
What I learned with Java Gold
What I learned with Java Silver
What I researched about Java learning