A symbol is an object that has a one-to-one correspondence with an arbitrary character string. The syntax of the symbol is that the symbol defines a colon (:) followed by any name.
: Symbol name
(Example)
:sushi
:ruby
:pen
:sushi.class # =>Symbol
'sushi'.class # =>String
Symbols are objects of the Symbol class The string is an object of the String class
string = 'sushi'
string.upcase! # => "SUSHI"
#Symbols are immutable, so destructive changes are not possible
symbol = :sushi
symbol.upcase! # => ruby.rb:5:in `<main>': undefined method `upcase!' for :sushi:Symbol (NoMethodError)
Strings can be destructively changed Symbol is impossible
Mutable means changeable
,
Immutable means immutable, immutable
.
Destructive changes can be applied to mutable objects such as strings. But, Destructive changes cannot be applied to immutable objects such as symbols. Therefore, the symbol is suitable for the purpose of "I want to give a name to something, because it is a name, I don't want anyone to change it without permission".
◎ 4 types of immutable objects are data types
--Numeric value: integer / float class --Symbol: symbol class --Boolean: true, false class --nil: nil class
――It looks like a character string on the surface, so it is easy for programmers to understand. --Because it is an integer internally, the computer can compare values at high speed. --The same symbol is the same object, so memory usage is good. -Since it is immutable, there is no need to worry about changing the value without permission.
Symbols are often used when you want to be able to identify a name in your source code, but the name does not necessarily have to be a string. A typical use case is a hash key. You can use symbols as hash keys to retrieve values faster than strings.
Introduction to Ruby for those who want to become a professional
Recommended Posts