设为首页 加入收藏

TOP

Ruby字符串(2):String方法详细整理(十一)
2019-08-15 00:10:18 】 浏览:357
Tags:Ruby 字符串 String 方法 详细 整理
nt y, x } #=> rceu lowlr

split

split(pattern=nil, [limit]) → an_array
split(pattern=nil, [limit]) {|sub| block } → str

将字符串切分成数组。

如果pattern部分是字符串,则这个字符串的内容作为切割字符串的分隔符。

如果pattern部分是单个空格,则切割时所有空白符号都被忽略,包括前缀或后缀空白,相当于是压缩了所有空格,然后分隔,且忽略前后缀空白。

如果没有给pattern,则采取变量$;的值作为分隔符,如果没有设置过$;,它默认等价于使用单个空格作为pattern。

如果pattern部分是空字符串(0长字符串),则对每个字符都进行分割。

如果pattern部分是正则表达式,则每次在匹配的时候进行分割。如果pattern中包含了分组捕获,则对应的匹配也会放进数组中。

如果要切割的字符串是空字符串,则返回空数组。

如果省略limit参数,则会抑制尾随空字段。如果limit是正数,则最多返回拆分子字符串的数量(捕获的组也将返回,但不会计算到极限)。如果limit为' 1 ',则返回整个字符串作为数组中的唯一条目。如果是负数,则不限制返回的字段的数量,并且不抑制尾随空字段。

If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that number of split substrings will be returned (captured groups will be returned as well, but are not counted towards the limit). If limit is 1, the entire string is returned as the only entry in an array. If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed.

" now's  the time ".split       #=> ["now's", "the", "time"]
" now's  the time ".split(' ')  #=> ["now's", "the", "time"]
"   hello  \tworld   ".split(" ")   #=> ["hello", "world"]

" now's  the time".split(/ /)   #=> ["", "now's", "", "the", "time"]
"1, 2.34,56, 7".split(%r{,\s*}) #=> ["1", "2.34", "56", "7"]
"hello".split(//)               #=> ["h", "e", "l", "l", "o"]
"hello".split(//, 3)            #=> ["h", "e", "llo"]
"hi mom".split(%r{\s*})         #=> ["h", "i", "m", "o", "m"]

"mellow yellow".split("ello")   #=> ["m", "w y", "w"]
"1,2,,3,4,,".split(',')         #=> ["1", "2", "", "3", "4"]
"1,2,,3,4,,".split(',', 4)      #=> ["1", "2", "", "3,4,,"]
"1,2,,3,4,,".split(',', -4)     #=> ["1", "2", "", "3", "4", "", ""]

"1:2:3".split(/(:)()()/, 2)     #=> ["1", ":", "", "", "2:3"]

"".split(',', -1)               #=> []

squeeze和squeeze!

squeeze([other_str]*) → new_str
squeeze!([other_str]*) → str or nil

压缩字符串中连续相同的字符为单个字符。

如果不给任何参数,则压缩所有连续相同的字符。

如果给参数,则从一个或多个参数中取交集。

"yellow moon".squeeze                  #=> "yelow mon"
"  now   is  the".squeeze(" ")         #=> " now is the"
"putters shoot balls".squeeze("m-z")   #=> "puters shot balls"
"putters shoot balls".squeeze("m-z","o")
    #=> "putters shot balls"        # 只有o被压缩了

tr和tr!

tr(from_str, to_str) => new_str
tr!(from_str, to_str) → str or nil

表示将字符串中所有from_str中出现的字符替换为一一映射到to_str中的字符。

"hello".tr('el', 'ip')      #=> "hippo"

这里e映射为il映射为p,表示将hello中的所有e替换为i,l替换为p。

如果to_str比from_str短,则将to_str的最后一个

首页 上一页 8 9 10 11 下一页 尾页 11/11/11
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇猫眼电影练习,动态字体 下一篇安装Ruby、多版本Ruby共存、Ruby..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目