Ruby字符串操作总结

后端开发   发布日期:2025年07月09日   浏览次数:287
字符串的整理如下:
、字符串定义与产生
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 = [,,,,]
puts arr.join(",")    #数组用join转换成字符串
、字符串操作
str = 'this' + " is"
str += ' you'
str <<" string"<<"."

puts str *  #this is you string.this is you string.
puts str[-,] # you string. 意味从后截取多少个字符
、转义字符串
\n
\t
\'
字符串转移只对双引号字符串生效,例外为单引号,如:
str = 'this\'s you string.'

字符串内嵌入表达式用  #{ }
def Hello(name)
  "Hello #{neme}!"
end


以上就是Ruby字符串操作总结的详细内容,更多关于Ruby字符串操作总结的资料请关注九品源码其它相关文章!