Ruby - 字符串

Page content

Ruby 中字符串类类型为 String, Ruby 2.0 默认使用 unicode 字符集,所以可以直接操作 UTF-8 字符串,无需转码。

> "Hello world".class
=> String
> '中国'.encoding.to_s
=> "UTF-8"

字符串赋值

字符串赋值(定义)用双引号或者单引号包含起来:

x = "A string"
y = 'A String'

多行字符串可以用 %q{} 包含,例如:

z = %q{This is a good project.
Just fork it.
}

其中%q 是固定格式,{} 可以替换为其它成对符号,例如:

<> ## !! 等

Ruby Doc 文档模式的字符串使用方法如下:

x = <<END_MY_STRING
This is the first string
And the second line
END_MY_STRING

其中 END_MY_STRING 可以自定义,当然必须以此结尾。

注意,多行字符串中的内容中间不能有边界符号,例如{},<>,或者自定义的服务,否则会导致错误。

快速定义字符串数组

使用 %w{}可以快速定义数组,例如

x = %w{1 2 3}
y = ["1","2","3"]
x == y    # true
x.class   # Array

x 和 y 是相等的。 %w{}使用空白符分隔字符串,多个空白符不当作数组元素。

字符串插写

类似于一些模板语言,Ruby 中字符串会自动进行变量替换,例如:

x = 10; y = 20;
puts "#{x} + #{y} = #{x+y}"

#输出
10 + 20 = 30

puts "It's a #{"bad"*5} idea"
#输出
It's a badbadbadbadbad idea

常见的字符串方法

字符串有一些常见的方法

"Test" + "Test"   "TestTest"
"Test".upcase     "TEST"
"Test".downcase   "test"
"Test".hash         117699239471428832
"Test".reverse      "tseT"
"Test".swapcase     "tEST"
"Test".reverse.upcase   "TSET"
"Test".length       4

字符串与正则表达式

字符串替换,例如:

'Hello world'.gsub(/rld/,'##')        "Hello wo##"
'Hello world'.sub(/.o/,'##')         "Hel## world"
'Hello world'.gsub(/.o/,'##')        "Hel## ##rld"

sub 和 gsub 的区别在于,sub 是单次替换,gsub 是全局替换。

“=~” 匹配字符串在原字符串中的位置,例如:

'Hello world' =~ /world/
=> 6

'Hello world' =~ /[l]+/
=> 2

match 方法既可以使用正则表达式也可以使用字符串,

'Hello world'.match(/[eo]/)
'Hello world'.match('[eo]')

puts 'matched' if 'Hello word'.match('[eo]')
#输出
matched