ruby and watir学习之_String 类

String类说明

函数名称

说明

示例

*

将字符串拷贝 N 次

ha*4 >>hahahaha

+

<<

concat

连接字符串

yes+no>>yesno"yes" << "no" >>yesno"yes".concat("no")

<=>

比较字符串,返回值如下: 大于:-1 等于:0 小于:1

"Ab" <=> "ab" >> -1 "ab" <=> "ab" >> 0

"ab" <=> "Ab" >> 1

=====

判断两个对象是否相等

"1" == "1" >>true

"1" == 1 >>flase

=~

匹配正则表达式

"abc123abc" =~ /\d/ >> 3

[ ]slice

返回字符串的某一范围内的值

abc[0,2] >>ab"hello"[/llo/] >>llo” “abcslice [0,2] >>ab

[ ]=

替换字符串的某一范围内的值

a =hello word

a[1,2]=OO

puts a >> hOOlo word

capitalize

capitalize!

把字符串的首字母大写,其他字母小写

"hi,Ruby".capitalize

>>Hi,ruby

chomp

chomp!

删除字符串后的空白字符

"string\r\n".chomp

>>string

chop

删除最后一个字符

"string".chop >>strin

count

返回该字符串中含的字符个数

a = "hello world" a.count "lo" >> 5

(l 出现 3 次,o 出现 2)

delete

delete!

删除字符

"hello".delete "l","lo"»"heo" "hello".delete "lo"»"he"

downcase downcase

将大写字母改写为小写

"hEllO".downcase»"hello"

upcase upcase

将小写字母改写为大写

"hEllO".upcase»"HELLO"

swapcase

swapcase!

将所有的大写字母改为小写字母,

小写字母改为大写字母。

"Hello".swapcase»"hELLO"

each

对字符串中的各行进行迭代操作

"Hi\nRuby". each { |s| puts s}

each_byte

对字符串中的各个字节进行迭代操作

"Hi\nRuby". each_byte { |s| puts s}

each_line

对字符串中的每一行进行迭代操作

"Hi\nRuby". each_line { |s| puts s}

empty?

判断字符串是否为空

"hello".empty?»false

"".empty?»true

gsub gsub

以 replace 来 替 换 字 符 串 中 所 有 与

pattern 相匹配的部分

"hello".gsub(/[aeiou]/, '*')»"h*ll*"

hash

返回字符串的哈希值

"h".hash >> 107

include?

若字符串中包含 substr 子字符串的话,

就返回真

"hello".include? "lo"»true

"hello".include? "ol"»false

index

按照从左到右的顺序搜索子字符串,并

返回搜索到的子字符串的左侧位置. 若 没有搜索到则返回 nil

"hello".index('lo')»3 "hello".index('a')»nil

length

返回字符串的字节数

"hello".length >> 5

replace

替换字符串的内容

s = "hello"»"hello" s.replace "world"»"world"

subsub!

replace 来替换首次匹配 pattern

部分。

"hello".sub(/[aeiou]/, '*')

»"h*llo"

reverse

reverse!

对字符串进行反转

"stressed".reverse»"desserts"

scan

使用正则表达式 re 反复对 self 进行匹

配操作,并以数组的形式返回匹配成功

的子字符串

a = "cruel world"

a.scan(/\w+/)»["cruel", "world"]

a.scan(/.../)»["cru", "el ", "wor"]

split

使用 sep 指定的 pattern 来分割字符

串,并将分割结果存入数组

"mellow yellow".split("ello")

»["m", "w y", "w"]

squeeze squeeze!

压缩由 str 所含字符构成的重复字符串

"yellow moon".squeeze

»"yelow mon"

" now is the".squeeze(" ")

»" now is the"

strip

strip!

删除头部和尾部的所有空白字符。空白

字符是指" \t\r\n\f\v"。

" hello ".strip»"hello" "\tgoodbye\r\n".strip»"goodbye"

trtr!

若字符串中包含 search 字符串中的字

符时,就将其替换为 replace 字符串中 相应的字符

hello".tr('aeiou', '*')»"h*ll*" "hello".tr('^aeiou', '*')»"*e**o"

tr_str_s

若字符串中包含 search 字符串中的字

符时,就将其替换为 replace 字符串中 相应的字符。同时,若替换部分中出现 重复字符串时,就将其压缩为 1 个字符

"hello".tr_s('l', 'r')»"hero" "hello".tr_s('el', '*')»"h*o" "hello".tr_s('el', 'hx')»"hhxo"

upto

在从 self 到 max 的范围内,依次取出

下一个字符串”后将其传给块,进行迭代

操作

"a1".upto("a3") {|s| puts s}

»a1\na2\na3

to_f

将字符串转为浮点数

"45.67 degrees".to_f»45.67

to_i

将字符串转为整数

"99 red balloons".to_i»99

to_s

将字符串转为字符串