] = new_str
# 3.根据索引范围,搜索或赋值0或多个元素
str[range] → new_str or nil
str[range] = aString
# 4.根据正则模式(斜线包围正则表达式),搜索或赋值匹配到的元素
str[regexp] → new_str or nil
str[regexp] = new_str
# 5.根据正则模式(包含分组匹配),返回给定分组内容
# capture可以是分组名,也可以是分组索引号(即反向引用)
# 分组索引号为0表示regexp匹配的所有内容
# 如果是赋值操作,则替换给定分组的内容
str[regexp, capture] → new_str or nil
str[regexp, integer] = new_str
str[regexp, name] = new_str
# 6.根据给定字符串精确搜索或赋值
str[match_str] → new_str or nil
str[other_str] = new_str
可以说,Ruby对字符串的索引操作支持的是相当的丰富、完善。下面是一些例子:
a = "hello there"
a[1] #=> "e"
a[2, 3] #=> "llo"
a[2..3] #=> "ll"
a[-3, 2] #=> "er"
a[7..-2] #=> "her"
a[-4..-2] #=> "her"
a[-2..-4] #=> ""
a[11, 0] #=> ""
a[11] #=> nil
a[12, 0] #=> nil
a[12..-1] #=> nil
a[/[aeiou](.)\1/] #=> "ell"
a[/[aeiou](.)\1/, 0] #=> "ell" 等价于上面方式
a[/[aeiou](.)\1/, 1] #=> "l" 第一个分组内容
a[/[aeiou](.)\1/, 2] #=> nil 第二个分组
a[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, "non_vowel"] #=> "l"
a[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, "vowel"] #=> "e"
a["lo"] #=> "lo"
a["bye"] #=> nil
s = "hello"
while(s["l"]) # 将所有的l替换成L
s["l"] = "L"
end
ascii_only?
ascii_only? → true or false
如果字符串中只包含ASCII字符,则返回true。
b
b → str
返回字符串的一个ASCII-8BIT编码的拷贝。
bytes
bytes → an_array
返回字符串各字符的字节数组。等价于a.each_byte.to_a
。
>> a=%q(hello) #=> "hello"
>> a.bytes #=> [104, 101, 108, 108, 111]
>> a.each_byte.to_a #=> [104, 101, 108, 108, 111]
chars
chars → an_array
返回字符串各字符的数组。等价于a.each_char.to_a
。
a="hello"
a.chars #=> ["h", "e", "l", "l", "o"]
a.each_char.to_a #=> ["h", "e", "l", "l", "o"]
lines
lines(separator=$/ [, getline_args]) → an_array
返回字符串中各行组成的数组。sep指定行分隔符(记录分隔符),getline_args支持的选项目前只有:chomp
。等价于a.each_line.to_a
。
"hello\nworld\n".lines #=> ["hello\n", "world\n"]
"hello world".lines(' ') #=> ["hello ", "world"]
"hello world".lines(' ') #=> ["hello ", " ", "world"]
"hello\nworld\n".lines(chomp: true) #=> ["hello", "world"]
"hello\nworld\n".each_line.to_a #=> ["hello\n", "world\n"]
codepoints
返回字符串各代码点的数组。等价于a.each_codepoint.to_a
。
"我是单身狗".codepoints
#=> [25105, 26159, 21333, 36523, 29399]
"我是单身狗".each_codepoint.to_a
#=> [25105, 26159, 21333, 36523, 29399]
bytesize
bytesize → integer
返回字符串的字节数量。
"\x80\u3042".bytesize #=> 4
"hello".bytesize #=> 5
"我".bytesize #=> 3
注:是字节长度不是字符数量。返回字符数量的是length()或size()。
size和length
length → integer
size → integer
返回字符串的字符数量。
"hello".size #=> 5
"我".size #=> 1
byteslice
byteslice(int) → new_str or nil
byteslice(int, len) → new_str or nil
byteslice(range) → new_str or nil
按字节截取字符串。字节索引可以为负数表示从尾部开始计算位置。
如果初始范围超出