设为首页 加入收藏

TOP

Ruby字符串(2):String方法详细整理(七)
2019-08-15 00:10:18 】 浏览:350
Tags:Ruby 字符串 String 方法 详细 整理
gt;" "hello".gsub(/./) {|s| s.ord.to_s + ' '} #=> "104 101 108 108 111 " "hello".gsub(/(?<foo>[aeiou])/, '{\k<foo>}') #=> "h{e}ll{o}" 'hello'.gsub(/[eo]/, 'e' => 3, 'o' => '*') #=> "h3ll*"

sub

sub(pattern, replacement) → new_str
sub(pattern, hash) → new_str
sub(pattern) {|match| block } → new_str

sub!(pattern, replacement) → str or nil
sub!(pattern) {|match| block } → str or nil

类似于gsub,但只替换一次。

"hello".sub(/[aeiou]/, '*')                  #=> "h*llo"
"hello".sub(/([aeiou])/, '<\1>')             #=> "h<e>llo"
"hello".sub(/./) {|s| s.ord.to_s + ' ' }     #=> "104 ello"
"hello".sub(/(?<foo>[aeiou])/, '*\k<foo>*')  #=> "h*e*llo"
'Is SHELL your preferred shell?'.sub(/[[:upper:]]{2,}/, ENV)
    #=> "Is /bin/bash your preferred shell?"

hash

hash → integer

根据字符串的长度、内容、编码生成hash值。在使用eql?比较的时候,所采用的比较依据就是hash值。

>> "hello".hash
=> -1983722257626684531
>> "h".hash
=> 2851888847349797667

下面是eql?()只当不同编码时的比较过程。

>> "我".encode("utf-8").eql?( "我".encode("utf-16") )
=> false

>> "hello".encode("utf-8").eql?( "hello".encode("utf-16") )
=> false

>> "hello".encode("utf-8").eql?( "hello".encode("gbk") )
=> true

hex

hex → integer

将字符串以16进制的方式解析并转换成10进制数值。所以,它是16进制 -> 10进制

如果字符串中存在了16进制解析不了的字符(即超出了0-9a-zA-Z)的字符,则返回0。但注意,对于字符0,它从16进制转换成10进制也返回0。

字符串的前缀如果是0x0X,则解析时自动识别它,不认为是需要解析的字符串。

>> "9".hex     #=> 9
>> "a".hex     #=> 10
>> "e".hex     #=> 14
>> "f".hex     #=> 15
>> "10".hex    #=> 16

>> "0xa".hex   #=> 10
>> "0Xa".hex   #=> 10
>> "0XA".hex   #=> 10
>> "-0xa".hex  #=> -10
>> "-23".hex   #=> -35

>> "0".hex     #=> 0
>> "g".hex     #=> 0

oct

oct → integer

将字符串以8进制的方式解析并转换成10进制数值。所以,它是8进制 -> 10进制

如果以8进制(只能识别0-7)的方式解析字符串时出错,返回0。但注意,对于字符0,它从8进制转换成10进制也返回0。

字符串的前缀如果是0,则解析时自动识别它,不认为是需要解析的字符串。

"123".oct       #=> 83
"-377".oct      #=> -255
"bad".oct       #=> 0
"0377bad".oct   #=> 255

ord

ord → integer

返回字符串第一个字符的数值。

"a".ord         #=> 97
"hello".ord     #=> 104
"h".ord         #=> 104
"我".ord        #=> 25105

include?

include? other_str → true or false

判断字符串中是否包含某个字符或某个子串。

>> "hello".include?("ll")  #=> true
>> "hello".include?("L")   #=> false
>> "hello".include?("")    #=> true

index和rindex

index(substring [, offset]) → integer or nil
index(regexp [, offset]) → integer or nil

rindex(substring [, integer]) → integer or nil
rindex(regexp [, integer]) → integer or nil

返回给定子串或正则模式所匹配内容的(从左或从右)第一个匹配的位置。也就是搜索字符串中是否包含某子串(或正则模式),并返回它的索引位置。

如果没有匹配到内容,则返回nil。

如果给定了第二个参数offset,则表示从此offset处开始向后搜索。

"hello".index('e')             #=> 1
"hello".index('lo')            #=> 3
&quo
首页 上一页 4 5 6 7 8 9 10 下一页 尾页 7/11/11
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇猫眼电影练习,动态字体 下一篇安装Ruby、多版本Ruby共存、Ruby..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目