gt; x="hello" #=> "hello"
>> x.object_id #=> 11676080
>> y=x.freeze #=> "hello" # x和y是同一对象,都不可变
>> y.object_id #=> 11676080
?> x[1]="E" # RuntimeError: can't modify frozen String
>> y[1]="E" # RuntimeError: can't modify frozen String
比较字符串
string <=> other_string → -1, 0, +1, or nil
str == obj → true or false
str != obj → true or false
str === obj → true or false
eql?(other) → true or false
equal? → true or false
比较字符串大小:
- 左边小于右边,则返回-1
- 左边等于右边,则返回0
- 左边大于右边,则返回1
- 两者不可比较(比如一方不是字符串),则返回nil
有了<=>
之后,就默认有了<、<=、> 、>=
和between?
方法。
对于字符串而言,==
、===
和eql?
是等价的,都用于比较字符串是否相同,String遵守了Ruby对equal?
的设计要求:不要轻易去重写equal?
,所以String直接从BasicObject中继承了equal?
,它比较的是两者是否是同一对象。
"abcdef" <=> "abcde" #=> 1
"abcdef" <=> "abcdef" #=> 0
"abcdef" <=> "abcdefg" #=> -1
"abcdef" <=> "ABCDEF" #=> 1
"abcdef" <=> 1 #=> nil
"abc" == "abc" #=> true
"abc" === "abc" #=> true
"abc".eql? "abc" #=> true
"abc".equal? "abc" #=> false
to_f、to_i、to_r
to_s、to_str
to_sym
# str向数值类转换
to_f → float
to_i(base=10) → int
to_r → rational
# str向字符串转换
to_s → str
to_str → str
# str向symbol转换
to_sym → symbol
to_f
表示将字符串转换成浮点数,从头部开始转换,尾部无效字符会忽略。无法转换时返回0.0
。
"123.45e1".to_f #=> 1234.5
"45.67 degrees".to_f #=> 45.67
"thx1138".to_f #=> 0.0
to_i
表示将字符串转换成整型数,从头部开始转换,尾部无效字符会忽略。无法转换时返回0
。可以指定base=N
参数来控制如何解析字符串,例如指定base=16
时,那么就能识别字符串的a字符。
"12345".to_i #=> 12345
"99 red balloons".to_i #=> 99
"0a".to_i #=> 0
"0a".to_i(16) #=> 10
"hello".to_i #=> 0
"1100101".to_i(2) #=> 101
"1100101".to_i(8) #=> 294977
"1100101".to_i(10) #=> 1100101
"1100101".to_i(16) #=> 17826049
to_r
表示将字符串转换成分数形式。忽略前缀空白以及后缀无效字符。
' 2 '.to_r #=> (2/1)
'300/2'.to_r #=> (150/1)
'-9.2'.to_r #=> (-46/5)
'-9.2e2'.to_r #=> (-920/1)
'1_234_567'.to_r #=> (1234567/1)
'21 June 09'.to_r #=> (21/1)
'21/06/09'.to_r #=> (7/2)
'BWV 1079'.to_r #=> (0/1)
注意,"0.3".to_r
和0.3.to_r
是不同的,后者是浮点数转换为分数,而浮点数是不精确的,比如这里假设0.3等于0.30000000000009
,那么0.3.to_r
等价于"0.30000000000009".to_r
。
关于to_sym
,等价于intern,参见intern。
=~正则匹配字符串
str =~ obj → integer or nil
- 如果obj是一个正则表达式,则用此正则去匹配str,匹配成功则返回匹配到的第一个字符的位置,否则返回nil
- 如果obj不是正则表达式,则调用
obj.=~(str)
,即调用obj的=~
方法,然后以str作为参数
注:str =~ reg 和 reg =~ str是不同的,如果reg里有命名捕获,则只有第二种才会将捕获到的内容赋值到对应的变量当中。所以在Ruby中,强烈建议将reg放在前面,这和Perl的位置顺序是相反的。
>> "hello" =~ /(?<x>e)/ #=> 1
>> x # NameError: undefined local variable or method `x' for main:Object
>> /(?<x>e)/ =~ "hello" #=> 1
>> x #=> "e"
索引、搜索和赋值
slice和slice!
字符串可变、可索引子串、设置子串、插入子串、删除子串等等。
通过[]
可以对字符串进行搜索和赋值,赋值时是原处修改字符串的。索引方式有多种,且支持负数索引号。
此外,slice()
和slice!()
分别等价于str[]
搜索和str[] = xxx
赋值。
# 1.根据索引,搜索或赋值单元素
str[index] → new_str or nil
str[index] = new_str
# 2.根据索引和给定长度,搜索或赋值0或多个元素
str[start, length] → new_str or nil
str[index, integer