[Ruby] Today’s memo (percent notation, string operation, symbol)

1 minute read

Percent notation

You can specify a sign to enclose a character string enclosed in “’” or “”” in percent notation. When you use “”” in a string, you don’t have to escape it.

Example

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

# There is """
a = %*"TEST"*
p a #=> "\"TEST\""
Format Generated value
% Double quote string
%Q Double quote string
%q Single quote string
%s Symbol
%x Command output
%r Regular Expression

String operation

In the character string, “+” and “*” can be applied and connected.

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

In addition, you can also use “«” when connecting at the end.

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

Although it is ***, an error occurs when concatenating different character codes (UTF-8 and SJIS, etc.). **

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

symbol

Symbols are mainly defined by putting “:” before 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

You can also generate symbols using the percent notation.

%s*test* #=> :test

How to generate a symbol from a string

a1 = "test"
a2 = a1.to_sym # use the to_sym method
p a2.class #=> Symbol

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

Tags:

Updated: