Ruby字符串操作总结
字符串的整理如下:
1、字符串定义与产生
str1 = 'Hello world'
str2 = "Hello world" #双引号比单引号定义的字符串更加强大,如可提供转移字符等
str3 = %q/Hello world/ # %q将后面的字符串转换成单引号字符串,后面的/为自定义的特殊符号,在字符串结尾处也需有该特殊符号
str4 = %Q/Hello world/ # %Q将定义双引号字符串
str = <<The_Text
Hello
World!
Hello
Ruby.
The_Text
puts str #这种方式比较有意思,str的内容为<<The_Text到下个The_Text之间的内容,The_Text为自定义的文本
arr = [1,1,1,2,2]
puts arr.join(",") #数组用join转换成字符串
2、字符串操作
str = 'this' + " is"
str += ' you'
str <<" string"<<"."
puts str * 2 #this is you string.this is you string.
puts str[-12,12] # you string. 意味从后截取多少个字符
3、转义字符串
\n
\t
\'
字符串转移只对双引号字符串生效,例外为单引号,如:
str = 'this\'s you string.'
字符串内嵌入表达式用 #{ }
def Hello(name)
"Hello #{neme}!"
end
str1 = 'Hello world'
str2 = "Hello world" #双引号比单引号定义的字符串更加强大,如可提供转移字符等
str3 = %q/Hello world/ # %q将后面的字符串转换成单引号字符串,后面的/为自定义的特殊符号,在字符串结尾处也需有该特殊符号
str4 = %Q/Hello world/ # %Q将定义双引号字符串
str = <<The_Text
Hello
World!
Hello
Ruby.
The_Text
puts str #这种方式比较有意思,str的内容为<<The_Text到下个The_Text之间的内容,The_Text为自定义的文本
arr = [1,1,1,2,2]
puts arr.join(",") #数组用join转换成字符串
2、字符串操作
str = 'this' + " is"
str += ' you'
str <<" string"<<"."
puts str * 2 #this is you string.this is you string.
puts str[-12,12] # you string. 意味从后截取多少个字符
3、转义字符串
\n
\t
\'
字符串转移只对双引号字符串生效,例外为单引号,如:
str = 'this\'s you string.'
字符串内嵌入表达式用 #{ }
def Hello(name)
"Hello #{neme}!"
end