String

[] 中的索引

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[12..-1]              #=> nil

a[/[aeiou](.)\1/]      #=> "ell"

a[/[aeiou](.)\1/, 0]   #=> "ell"

a[/[aeiou](.)\1/, 1]   #=> "l"

a[/[aeiou](.)\1/, 2]   #=> nil

a["lo"]                #=> "lo"

a["bye"]               #=> nil

 

索引不但支持 用范围

 

还支持 逗号分隔的两个参数(1st=首索引,2nd==长度)

 

支持 负索引

 

支持 正则

 

 

str[fixnum] = new_str

str[fixnum, fixnum] = new_str

str[range] = aString

str[regexp] = new_str

str[regexp, fixnum] = new_str

str[regexp, name] = new_str

str[other_str] = new_str

按字节处理bytes

byte切片

byteslice(fixnum) new_str or nil

byteslice(fixnum, fixnum) new_str or nil

byteslice(range) new_str or nil

 

bytesize integer    Returns the length of str in bytes.

bytes {|fixnum| block } str

bytes an_enumerator

 

 

 

用正则替换

sub/gsub

"hello".gsub(/[aeiou]/, '*')                  #=> "h*ll*"

"hello".gsub(/([aeiou])/, '<\1>')             #=> "h<e>ll<o>"

"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*"

 

match

'hello'.match('(.)\1')      #=> #<MatchData "ll" 1:"l">

'hello'.match('(.)\1')[0]   #=> "ll"

'hello'.match(/(.)\1/)[0]   #=> "ll"

'hello'.match('xx')         #=> nil

 

partition

partition(sep) [head, sep, tail] click to toggle source

partition(regexp) [head, match, tail]

 

scan

a = "cruel world"

a.scan(/\w+/)        #=> ["cruel", "world"]

a.scan(/.../)        #=> ["cru", "el ", "wor"]

a.scan(/(...)/)      #=> [["cru"], ["el "], ["wor"]]

a.scan(/(..)(..)/)   #=> [["cr", "ue"], ["l ", "wo"]]

 

字符串转symbol

intern symbol

"Koala".intern         #=> :Koala

s = 'cat'.to_sym       #=> :cat

s == :cat              #=> true

s = '@cat'.to_sym      #=> :@cat

s == :@cat             #=> true

upto/downto/times/Range.each

 

 

 

 

你可能感兴趣的:(String)