设为首页 加入收藏

TOP

Ruby字符串(2):String方法详细整理(八)
2019-08-15 00:10:18 】 浏览:386
Tags:Ruby 字符串 String 方法 详细 整理
t;hello".index('a') #=> nil "hello".index(?e) #=> 1 "hello".index(/[aeiou]/, -3) #=> 4 "hello".rindex('e') #=> 1 "hello".rindex('l') #=> 3 "hello".rindex('a') #=> nil "hello".rindex(?e) #=> 1 "hello".rindex(/[aeiou]/, -2) #=> 1

replace

replace(other_str) → str

将字符串替换为另一个给定的字符串。注意是替换全部内容,且是原处修改对象

>> a="hello"           #=> "hello"
>> a.replace("world")  #=> "world"
>> a                   #=> "world"

insert

insert(index, other_str) → str

将给定字符串other_str插入到字符串的指定索引位置处。可以指定负数索引。注意是原处修改对象

a="hello"          #=> "hello"
a.insert(0,"good") #=> "goodhello"
a                  #=> "goodhello"

"abcd".insert(3, 'X')    #=> "abcXd"
"abcd".insert(4, 'X')    #=> "abcdX"
"abcd".insert(-3, 'X')   #=> "abXcd"
"abcd".insert(-1, 'X')   #=> "abcdX"

inspect

inspect → string

返回完全规范的字符串。所有需要转义的字符都会加上反斜线和双引号包围。

str = "hello"
str[3] = "\b"
str.inspect       #=> "\"hel\\bo\""

str.bytes         #=> [104, 101, 108, 8, 111]
>> p str          #=> "hel\bo"
>> puts str       # 输出heo

intern

intern → symbol

等价于to_sym,表示将字符串转换成symbol,如果symbol不存在,则新创建symbol对象。

"Koala".intern         #=> :Koala
s = 'cat'.to_sym       #=> :cat
s == :cat              #=> true
s = '@cat'.to_sym      #=> :@cat
s == :@cat             #=> true
'cat and dog'.to_sym   #=> :"cat and dog"

ljust和rjust

ljust(length, padstr=' ') → new_str
rjust(length, padstr=' ') → new_str

在字符串右、左边填充字符使得填充后字符串达到length长度。如果没有指定padstr则使用空格填充。如果length小于当前字符串长度,则不填充仅拷贝一个新字符串对象。

"hello".ljust(4)            #=> "hello"
"hello".ljust(20)           #=> "hello               "
"hello".ljust(20, '1234')   #=> "hello123412341234123"

"hello".rjust(4)            #=> "hello"
"hello".rjust(20)           #=> "               hello"
"hello".rjust(20, '1234')   #=> "123412341234123hello"

lstrip和lstrip!

rstrip和rstrip!

strip和strip!

lstrip → new_str
lstrip! → self or nil
rstrip → new_str
rstrip! → self or nil
strip → new_str
strip! → self or nil

移除字符串前缀、后缀空白。对于Xstrip!,如果没有进行移除操作,则返回nil。

"  hello  ".lstrip   #=> "hello  "
"  hello  ".rstrip   #=> "  hello"
"    hello    ".strip   #=> "hello"

"hello".lstrip       #=> "hello"
"hello".rstrip       #=> "hello"
"hello".strip           #=> "hello"

"\tgoodbye\r\n".strip   #=> "goodbye"
"\x00\t\n\v\f\r ".strip #=> ""

"  hello  ".lstrip!  #=> "hello  "
"  hello  ".rstrip!  #=> "  hello"
"  hello  ".strip!  #=> "hello"
"hello  ".lstrip!    #=> nil
"  hello".rstrip!    #=> nil
"hello".lstrip!      #=> nil
"hello".rstrip!      #=> nil
"hello".strip!      #=> nil

match和match?

match(pattern) → matchdata or nil
match(pattern, pos) → matchdata or nil

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

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目