Let's take a look at Ruby's String object using irb.
An object that handles character strings. Enclose it in single or double quotes to create a String object. Let's check with the class method.
$ irb
irb(main):001:0> "String".class
=> String
Here are some commonly used methods for String objects.
irb(main):002:0> 'String'.upcase
=> "STRING"
irb(main):007:0> 'String'.downcase
=> "string"
You can cut out the specified character string by using the slice method. In the example below, it is cut out from the 0th character to 2 (one before 3).
irb(main):006:0> 'String'.slice(0, 3)
=> "Str"
irb(main):014:0> 'String'.size
=> 6
Use a method called to_i.
irb(main):018:0> '10000'.class
=> String
irb(main):019:0> '10000'.to_i.class
=> Integer
Use a method called to_f.
irb(main):020:0> '1.1'.class
=> String
irb(main):021:0> '1.1'.to_f.class
=> Float
irb(main):027:0> 'Str' + 'ing'
=> "String"
irb(main):030:0> 'String' << '!'
=> "String!"
You can also concatenate continuously by using variables.
irb(main):038:0> str = 'String'
=> "String"
irb(main):039:0> str << '!'
=> "String!"
irb(main):040:0> str << '!'
=> "String!!"
irb(main):042:0> str = 'String'
=> "String"
irb(main):043:0> str += '!'
=> "String!"
If you embed the expression # {variable} in a string enclosed in double quotes Variables can be expanded in strings.
irb(main):047:0> name = 'Masuyama'
=> "Masuyama"
irb(main):048:0> "my name is#{name}is"
=> "My name is Masuyama"
By the way, not only variable expansion but also expression embedding and expansion is possible.
irb(main):052:0> "1 + 1 = #{1+1}"
=> "1 + 1 = 2"
Recommended Posts