1. String Object definition
The definition of a string object can use "and", for simple strings, it is recommended to use ' to define, ' the difference between efficiency and ' high, ' and ' is that ' the string defined in ' is the final form, even if the line-feed character is exported as it is, and ' is more like an expression, The parser handles the special characters and then outputs the following sample code:
Copy Code code as follows:
i = 100
S1 = ' The value of I variable is #{i}!\n ' #The value of i variable is #{i}!\n [output variable i value without newline]
S2 = "The value of I variable is #{i}!\n" #The value of i variable is 100! [Output the value of the I variable and line wrap]
String there is another way to define a string with a format, such as the following sample code:
Copy Code code as follows:
S3 = <<ok_str
The value
of I variable
Is #{i}
Ok_str
Output:
Copy Code code as follows:
The value
of I variable
is 100
A special string, using the ' defined string, is sent directly to the operating system as a system command, as shown in the following sample code:
Copy Code code as follows:
Puts ' ruby-v ' #输出: Ruby 1.9.3p392 (2013-02-22 revision 39386) [X86_64-linux]
Puts ' rails-v ' #输出: Rails 3.2.8
2. String Object operation
There are a lot of ways to manipulate String objects in Ruby, and you can refer to the official Ruby API documentation http://ruby-doc.org/core-2.0/String.html, which summarizes the unusual ways in which string strings work in other languages, as shown in the following sample code:
Copy Code code as follows:
x = ' ho! '
y = ' Hello from '
z = ' Hello '
Puts x*30 #输出: ho! Ho! Ho!
Puts y+self.to_s #输出: Hello from main
Puts z<< ' << ' world! ' #输出: Hello world!
Puts x.object_id #输出: 19196800
Puts (x*3). object_id #输出: 19196600
Puts y.object_id #输出: 19196780
Puts (y+self.to_s). object_id #输出: 19196520
Puts z.object_id #输出: 19196760
Puts (z<< ' << ' world! '). object_id #输出: 19196760
From the top code it is known that,<< is a string's append operation, returning the original object, + and * operations, and returning the new object.
3, you can use the array subscript to manipulate the characters in the string
Copy Code code as follows:
m = ' TaoBao '
#改变第二个字符a为o
M[1] = ' o '
Puts M
#截取第4到第6个字符的子字符串
Puts M[3..5]