Today's notes (percentage notation, string arithmetic, symbols)

Percentage notation

You can specify a symbol to enclose a character string enclosed in "'" or "" "in percent notation. You don't have to escape when you use "" "in a string.

Example

#『""None
a = %*TEST*
p a  #=> "TEST"

#『"』Yes
a = %*"TEST"*
p a  #=> "\"TEST\""
Format Generated value
% Double quoted string
%Q Double quoted string
%q Single quote string
%s symbol
%x Command output
%r Regular expressions

String operation

Character strings can be concatenated by applying "+" and "*".

a = "ru" + "by"
puts a    #=> ruby

You can also use "<<" to concatenate at the end.

a = "ru"
puts a << "by"    #=> ruby

** * However, an error will occur if different character codes (UTF-8 and SJIS, etc.) are concatenated. ** **

Addendum: For string comparison, you can refer to the number of characters with the length and size methods.

symbol

Symbols are mainly defined by putting ":" in front of the character string. However, it is not necessary to enclose the character string with "" ".

a = "ruby"
b = :study
 
p str.class    #=> String
p sym.class    #=> Symbol

Symbols can also be generated using percent notation.

%s*test*    #=> :test

How to generate a symbol from a string

a1 = "test"
a2 = a1.to_sym    # to_Use sym method
p a2.class    #=> Symbol

The created symbol will refer to the same object ID if the character sequence is the same, In the case of a string literal, even if the character sequence is the same, a new object is created each time, so the object ID changes.

Recommended Posts

Today's notes (percentage notation, string arithmetic, symbols)