这篇文章主要介绍了Ruby中操作字符串的一些基本方法,包括对字符串的压缩和解压缩等处理,需要的朋友可以参考下
在Ruby中的String对象持有和操纵的任意序列的一个或多个字节,通常表示人类语言的字符表示。
简单的字符串文本括在单引号(单引号字符)。引号内的文本的字符串值:
?
1 'This is a simple Ruby string literal'如果需要内放置一个单引号,单引号的字符串文字,在它前面加上一个反斜杠Ruby解释器不认为终止字符串:
?
1 'Won't you read O'Reilly's book?'反斜杠也可以转义另一个反斜杠,这样第二个反斜杠本身不是解释为转义字符。
以下是字符串相关的功能Ruby的。
表达式替换:
表达式替换嵌入任何Ruby表达式的值转换成字符串使用的一种手段,可用 #{ and }替换:
?
1 2 3 4 5 6 #!/usr/bin/ruby x, y, z = 12, 36, 72 puts "The value of x is #{ x }." puts "The sum of x and y is #{ x + y }." puts "The average was #{ (x + y + z)/3 }."这将产生以下结果:
?
1 2 3 The value of x is 12. The sum of x and y is 48. The average was 40.一般分隔的字符串:
一般分隔的字符串,可以创建字符串匹配任意分隔符,比如,虽然包含在一对,如:., !, (, {, <, 等,前面加上一个百分号(%). Q, q 和 x,有特殊的含义一般可以分隔的字符串。
?
1 2 3 4 %{Ruby is fun.} equivalent to "Ruby is fun." %Q{ Ruby is fun. } equivalent to " Ruby is fun. " %q[Ruby is fun.] equivalent to a single-quoted string %x!ls! equivalent to back tick command output `ls`转义字符:
下表是转义或反斜线符号可以表示非打印字符列表。
注: 在双引号的字符串,被解释为转义字符,在一个单引号字符的转义字符被保留。

字符编码方式:
Ruby的默认字符集是ASCII码,字符可能会由单字节表示。如果使用UTF-8或另一种现代的字符集,字符可能会以四个字节表示。
可以更改字符集使用$KCODE的在程序的开始行,像这样:
?
1 $KCODE = 'u'以下是 $KCODE 可能的值

字符串的内置方法:
我们需要有一个String对象实例调用一个String方法。以下的方法来创建String对象的一个实例:
?
1 new [String.new(str="")]这将返回一个新的字符串对象,其中包含str的一个副本。现在使用str的对象,我们可以任何可用实例方法的。例如:
?
1 2 3 4 #!/usr/bin/ruby myStr = String.new("THIS IS TEST") foo = myStr.downcase?
1 puts "#{foo}"这将产生以下结果:
?
1 this is test字符串的解压指令:
下表列出了解压指令方法 String#unpack.



例子:
试试下面的例子来解压缩各种数据。
?
1 2 3 4 5 6 7 8 "abc abc ".unpack('A6Z6') #=> ["abc", "abc "] "abc ".unpack('a3a3') #=> ["abc", " 0000"] "abc abc ".unpack('Z*Z*') #=> ["abc ", "abc "] "aa".unpack('b8B8') #=> ["10000110", "01100001"] "aaa".unpack('h2H2c') #=> ["16", "61", 97] "xfexffxfexff".unpack('sS') #=> [-2, 65534] "now=20is".unpack('M*') #=> ["now is"] "whole".unpack('xax2aX2aX1aX2a') #=> ["h", "e", "l", "l", "o"]