Ruby字符串(2):String方法詳細整理

String方法整理

官方手冊html

類方法

new

new(str="") → new_str
new(str="", encoding: enc) → new_str
new(str="", capacity: size) → new_str

encoding指定建立什麼編碼的字符串,即new_str是什麼編碼的。前端

capacity指定建立字符串對象時預先分配好的buffer大小。若是之後要擴容該字符串,就不須要再臨時動態分配內存。對於後續可能須要頻繁擴展該字符串的狀況,能夠提高一些性能。正則表達式

例如:shell

try_convert

try_convert(obj) → string or nil

嘗試經過調用to_s()將obj轉換成字符串,若是不能轉換,則不報錯而是返回nil。api

String.try_convert("hello")  #=> "hello"
String.try_convert(/re/)     #=> nil

實例方法

%格式化字符串

str % arg → new_str

arg有三種方式:單參數、數組、hash數組

"%05d" % 123                          #=> "00123"
"%-3s: %05d" % [ "ID", 123 ]          #=> "ID : 00123"
"foo = %{foo}" % { :foo => 'bar' }    #=> "foo = bar"

除了%,還有sprintf()(Kernel模塊中)也能夠格式化字符串。ruby

*重複字符串

str * integer → new_str

integer必須是大於等於0的整數,表示重複str字符串N次。重複0次表示返回空字符串。bash

"Ho! " * 3   #=> "Ho! Ho! Ho! "
"Ho! " * 0   #=> ""

+串聯擴展字符串

str + other_str → new_str

將other_str串聯追加到str的尾部。注意,返回的是新字符串對象,而不是原處修改的koa

a="hello"

a + self.to_s  #=> "hellomain"

puts a         #=> "hello"

<<和concat和prepend原處追加字符串

str << obj → str
str << integer → str
concat(obj1, obj2, ...) → str
prepend(other_str1, other_str2, ...) → str

將給定obj對象追加到str的尾部,很常常的,obj會是另外一個字符串對象,表示將另外一個字符串追加到str尾部進行擴展。注意是原處修改的ide

若是追加的是一個integer,則integer被看成是代碼點(或ASCII碼),因而將對應的字符插入到str的尾部。

若是obj不能轉換成字符串(經過to_str方法而不是to_s方法),則報錯,例如Array對象有to_s可是沒有to_str方法,因此Array不能追加到str尾部。

<<能夠多個串聯在一塊兒,例如a <<"hello" <<"world"

concat功能和<<同樣,它能夠接收多個參數。它也是原處修改對象

a = "hello "
a << "world"   #=> "hello world"
a << 33        #=> "hello world!"

b = "hello
b << "xyz" <<"hello"
b              #=> "helloxyzhello"

a="hello"
a.concat("world","nihao")  #=>helloworldnihao

prepend()是將一個或多個其它字符串插入到字符串的前端。它也是原處修改對象。

a = "!"
a.prepend("hello ", "world") #=> "hello world!"
a                            #=> "hello world!"

+-可變和不可變(frozen)字符串

+str → str (mutable)
-str → str (frozen)
freeze()

+str表示返回一個可變的字符串對象:

  • 若是原始字符串是frozen的,則拷貝一份並返回它的可變對象
  • 若是原始字符串自己就是可變的(字符串默認就是可變的),則返回自身,不拷貝字符串對象

-str表示返回一個不可變(frozen)的字符串對象:

  • 若是原始字符串是可變的,則拷貝一份
  • 若是原始字符串自己不可變,則返回自身

freeze()也表示返回不可變字符串對象,它都是在原處修改的。

因此,[+ -]str可能會建立新對象,而freeze則老是使得原始字符串不可變。

>> a="world"     #=> "world"
>> a.object_id   #=> 15976580

>> b = +a        #=> "world"
>> b.object_id   #=> 15976580  # 由於a自己可變,因此不拷貝,返回自身

>> a="world"     #=> "world"
>> a.object_id   #=> 8911880

>> b=-a          #=> "world"
>> b.object_id   #=> 8897840   # 由於a可變,因此拷貝,返回新的不可變對象b
>> b[1]="OO"     # b不可變,RuntimeError: can't modify frozen String

>> a[1]="OO"     # a仍然可變
=> "OO"
>> a
=> "wOOrld"

>> b.object_id   #=> 8854280
>> c = -b        #=> "world"    # b不可變,因此-b返回自身
>> c.object_id   #=> 8854280

>> d = +b        #=> "world"    # b不可變,因此+b建立新對象
>> d.object_id   #=> 11837980

>> x="hello"     #=> "hello"
>> x.object_id   #=> 11676080

>> y=x.freeze    #=> "hello"  # x和y是同一對象,都不可變
>> y.object_id   #=> 11676080
?> x[1]="E"      # RuntimeError: can't modify frozen String
>> y[1]="E"      # RuntimeError: can't modify frozen String

比較字符串

string <=> other_string → -1, 0, +1, or nil
str == obj → true or false
str != obj → true or false
str === obj → true or false
eql?(other) → true or false
equal? → true or false

比較字符串大小:

  • 左邊小於右邊,則返回-1
  • 左邊等於右邊,則返回0
  • 左邊大於右邊,則返回1
  • 二者不可比較(好比一方不是字符串),則返回nil

有了<=>以後,就默認有了<、<=、> 、>=between?方法。

對於字符串而言,=====eql?是等價的,都用於比較字符串是否相同,String遵照了Ruby對equal?的設計要求:不要輕易去重寫equal?,因此String直接從BasicObject中繼承了equal?,它比較的是二者是不是同一對象。

"abcdef" <=> "abcde"     #=> 1
"abcdef" <=> "abcdef"    #=> 0
"abcdef" <=> "abcdefg"   #=> -1
"abcdef" <=> "ABCDEF"    #=> 1
"abcdef" <=> 1           #=> nil

"abc" == "abc"      #=> true
"abc" === "abc"     #=> true
"abc".eql? "abc"    #=> true
"abc".equal? "abc"  #=> false

to_f、to_i、to_r

to_s、to_str

to_sym

# str向數值類轉換
to_f → float
to_i(base=10) → int
to_r → rational

# str向字符串轉換
to_s → str
to_str → str

# str向symbol轉換
to_sym → symbol

to_f表示將字符串轉換成浮點數,從頭部開始轉換,尾部無效字符會忽略。沒法轉換時返回0.0

"123.45e1".to_f        #=> 1234.5
"45.67 degrees".to_f   #=> 45.67
"thx1138".to_f         #=> 0.0

to_i表示將字符串轉換成整型數,從頭部開始轉換,尾部無效字符會忽略。沒法轉換時返回0。能夠指定base=N參數來控制如何解析字符串,例如指定base=16時,那麼就能識別字符串的a字符。

"12345".to_i             #=> 12345
"99 red balloons".to_i   #=> 99
"0a".to_i                #=> 0
"0a".to_i(16)            #=> 10
"hello".to_i             #=> 0
"1100101".to_i(2)        #=> 101
"1100101".to_i(8)        #=> 294977
"1100101".to_i(10)       #=> 1100101
"1100101".to_i(16)       #=> 17826049

to_r表示將字符串轉換成分數形式。忽略前綴空白以及後綴無效字符。

'  2  '.to_r       #=> (2/1)
'300/2'.to_r       #=> (150/1)
'-9.2'.to_r        #=> (-46/5)
'-9.2e2'.to_r      #=> (-920/1)
'1_234_567'.to_r   #=> (1234567/1)
'21 June 09'.to_r  #=> (21/1)
'21/06/09'.to_r    #=> (7/2)
'BWV 1079'.to_r    #=> (0/1)

注意,"0.3".to_r0.3.to_r是不一樣的,後者是浮點數轉換爲分數,而浮點數是不精確的,好比這裏假設0.3等於0.30000000000009,那麼0.3.to_r等價於"0.30000000000009".to_r

關於to_sym,等價於intern,參見intern

=~正則匹配字符串

str =~ obj → integer or nil
  • 若是obj是一個正則表達式,則用此正則去匹配str,匹配成功則返回匹配到的第一個字符的位置,不然返回nil
  • 若是obj不是正則表達式,則調用obj.=~(str),即調用obj的=~方法,而後以str做爲參數

注:str =~ reg 和 reg =~ str是不一樣的,若是reg裏有命名捕獲,則只有第二種纔會將捕獲到的內容賦值到對應的變量當中。因此在Ruby中,強烈建議將reg放在前面,這和Perl的位置順序是相反的

>> "hello" =~ /(?<x>e)/  #=> 1
>> x  # NameError: undefined local variable or method `x' for main:Object

>> /(?<x>e)/ =~ "hello"  #=> 1
>> x                     #=> "e"

索引、搜索和賦值

slice和slice!

字符串可變、可索引子串、設置子串、插入子串、刪除子串等等。

經過[]能夠對字符串進行搜索和賦值,賦值時是原處修改字符串的。索引方式有多種,且支持負數索引號。

此外,slice()slice!()分別等價於str[]搜索和str[] = xxx賦值。

# 1.根據索引,搜索或賦值單元素
str[index] → new_str or nil
str[index] = new_str

# 2.根據索引和給定長度,搜索或賦值0或多個元素
str[start, length] → new_str or nil
str[index, integer] = 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

按字節截取字符串。字節索引能夠爲負數表示從尾部開始計算位置。

若是初始範圍超出邊界或len爲負數,則返回nil。

"hello".byteslice(1)     #=> "e"
"hello".byteslice(-1)    #=> "o"
"hello".byteslice(1, 2)  #=> "el"
"\x80\u3042".byteslice(1, 3) #=> "\u3042"
"\x03\u3042\xff".byteslice(1..3) #=> "\u3042"

capitalize和capitalize!

capitalize → new_str
capitalize([options]) → new_str

capitalize! → str or nil
capitalize!([options]) → str or nil

將字符串首字母轉換成大寫字母,剩餘的轉換成小寫字母。

對於capitalize!,若是沒有作任何轉換操做,則返回nil。

關於options選項,主要和編碼有關,參見downcase

"hello".capitalize    #=> "Hello"
"HELLO".capitalize    #=> "Hello"
"123ABC".capitalize   #=> "123abc"

a = "hello"
a.capitalize!   #=> "Hello"
a               #=> "Hello"
a.capitalize!   #=> nil

downcase和downcase!

downcase → new_str
downcase([options]) → new_str

downcase! → str or nil
downcase!([options]) → str or nil

將字符串轉換成小寫字母。

對於downcase!,若是沒有作任何轉換操做,則返回nil。

關於options選項,主要和編碼有關,參見downcase

"hEllO".downcase   #=> "hello"

upcase和upcase!

upcase → new_str
upcase([options]) → new_str

upcase! → str or nil
upcase!([options]) → str or nil

將字符串轉換成大寫字母。

對於upcase!,若是沒有作任何轉換操做,則返回nil。

關於options選項,主要和編碼有關,參見downcase

>> "hello".upcase  #=> "HELLO"

swapcase和swapcase!

swapcase → new_str
swapcase([options]) → new_str

swapcase! → str or nil
swapcase!([options]) → str or nil

大小寫互換:大寫轉小寫、小寫轉大寫。對於swapcase!,若是沒有進行轉換操做,則返回nil。

"Hello".swapcase          #=> "hELLO"
"cYbEr_PuNk11".swapcase   #=> "CyBeR_pUnK11"

casecmp和casecmp?

casecmp(other_str) → -1, 0, +1, or nil
casecmp?(other_str) → true, false, or nil

casecmp實現了大小寫無關的<=>操做。若是編碼不一樣或一方不是字符串,則返回nil。

casecmp?考慮編碼,將字符串解碼後進行等值比較。相等則返回true,不等則返回false,若是編碼不一樣或一方不是字符串,則返回nil。

"1234abc".casecmp("1234ABC")  #=> 0

"我".casecmp("我") #=> 0

"\u{c4 d6 dc}" #=> "ÄÖÜ"
"\u{e4 f6 fc}" #=> "äöü"

"\u{c4 d6 dc}".casecmp("\u{e4 f6 fc}")  #=> -1
"\u{c4 d6 dc}".casecmp?("\u{e4 f6 fc}") #=> true

center

center(width, padstr=' ') → new_str

將字符串居中,左右兩邊填充padstr(默認爲空格)。若是字符串的字符數量大於width,則返回拷貝後的相等字符串。

"hello".center(4)         #=> "hello"
"hello".center(20)        #=> "       hello        "
"hello".center(20, '123') #=> "1231231hello12312312"

chomp和chomp!

chomp(separator=$/) → new_str
chomp!(separator=$/) → str or nil

移除字符串尾部的單個換行符(嚴格地說是$/指定的記錄分隔符),包括\n\r\r\n。但注意,尾部若是是\n\r,則只移除\r而留下\n

若是指定了separator,則移除尾部的這些字符串。

若是separator指定爲空字符串,則移除尾部全部連續的換行符。

若是尾部沒有換行符,即不須要移除。對於chomp,直接拷貝字符串並返回新對象,對於chomp!則返回nil。

"hello".chomp                #=> "hello"
"hello\n".chomp              #=> "hello"
"hello\r\n".chomp            #=> "hello"
"hello\n\r".chomp            #=> "hello\n"
"hello\r".chomp              #=> "hello"
"hello \n there".chomp       #=> "hello \n there"
"hello".chomp("llo")         #=> "he"
"hello\r\n\r\n".chomp('')    #=> "hello"
"hello\r\n\r\r\n".chomp('')  #=> "hello\r\n\r"

chop和chop!

chop → new_str
chop! → str or nil

移除字符串的最後一個字符。

若是字符串是空字符串,則chop直接返回一個空字符串,而chop!返回nil。

"string\r\n".chop   #=> "string"
"string\n\r".chop   #=> "string\n"
"string\n".chop     #=> "string"
"string".chop       #=> "strin"
"x".chop.chop       #=> ""

chr返回首字符

chr → string

返回字符串的首字符。

a = "abcde"
a.chr    #=> "a"

"我是單身狗".chr  #=> "我"

clear

clear → string

清空字符串。注意是原地修改的。

a = "abcde"
a.clear    #=> ""
a          #=> ""

count

count([other_str]+) → integer

從字符串中搜索給定字符的數量。多個other_str參數的交集肯定要搜索的字符。支持^取反語義以及-取範圍。若是要搜索這兩個特殊字符自己,使用反斜線轉義。

a = "hello world"
a.count "lo"                   #=> 5
a.count "lo", "o"              #=> 2,2個o
a.count "lo", "l"              #=> 3,3個l
a.count "hello", "^l"          #=> 4,heo共四個
a.count "ej-m"                 #=> 4,el共四個

"hello^world".count "\\^aeiou" #=> 4,^eo共4個
"he-llo-wor-ld".count "a\\-eo" #=> 6,-eo共6個

c = "hello world\\r\\n"
c.count "\\"                   #=> 2
c.count "\\A"                  #=> 0
c.count "X-\\w"                #=> 3

delete和delete!

delete([other_str]+) → new_str
delete!([other_str]+) → str or nil

刪除字符串中的某些字符,返回刪除後的字符串。

對於delete!,若是沒有字符要刪除,則返回nil。

other_str的規則和countother_str規則一致。

"hello".delete "l","lo"        #=> "heo"
"hello".delete "lo"            #=> "he"
"hello".delete "aeiou", "^e"   #=> "hell"
"hello".delete "ej-m"          #=> "ho"

delete_prefix和delete_prefix!

delete_suffix和delete_suffix!

delete_prefix(prefix) → new_str
delete_prefix!(prefix) → self or nil

delete_suffix(suffix) → new_str
delete_suffix!(suffix) → self or nil

從字符串頭部或者字符串尾部刪除指定的前綴、後綴。

若是沒有須要刪除的內容,對於delete_xxx,返回內容相同的新對象,對於delete_xxx!,則返回nil。

迭代each_xxx

包括each_byte、each_char、each_codepoint、each_line。

參見:字符串的迭代

up_to

upto(other_str, exclusive=false) {|s| block } → str
upto(other_str, exclusive=false) → an_enumerator

看例子:

"a8".upto("b6") {|s| print s, ' ' }
    #=> a8 a9 b0 b1 b2 b3 b4 b5 b6

for s in "a8".."b6"
  print s, ' '
end
    #=> a8 a9 b0 b1 b2 b3 b4 b5 b6
"9".upto("11").to_a   #=> ["9", "10", "11"]
"25".upto("5").to_a   #=> []
"07".upto("11").to_a  #=> ["07", "08", "09", "10", "11"]

empty?

empty? → true or false

判斷字符串是否爲空字符串。

"hello".empty?   #=> false
" ".empty?       #=> false
"".empty?        #=> true

encoding

encoding → encoding

返回字符串所使用的編碼對象(Encoding Object)。

今後也能夠知道所使用的是哪一個編碼。

>> var = "hello world"
>> var.encoding         #=> #<Encoding:UTF-8>
>> var.encoding.to_s    #=> "UTF-8"

encode和encode!

(1) encode(encoding [, options] ) → str
(2) encode(dst_encoding, src_encoding [, options] ) → str
(3) encode([options]) → str
 
(4) encode!(encoding [, options] ) → str
(5) encode!(dst_encoding, src_encoding [, options] ) → str

第(1)種表示轉換成指定編碼的新字符串對象。

第(2)種表示從src_encoding轉換成dst_encoding編碼的字符串對象。

第(3)種表示拷貝一個新字符串對象,編碼不變。

>> var = "hello world"
>> var_gbk = var.encode("gbk")  #=> "hello world"
>> var_gbk.encoding.to_s        #=> "GBK"

>> var_default = var_gbk.encode() #=> "hello world"
>> var_default.encoding.to_s    #=> "GBK"

options參見http://ruby-doc.org/core-2.6.2/String.html#method-i-encode

force_encoding

force_encoding(encoding) → str

強制將字符串的編碼轉換爲指定編碼。注意,是原處修改

>> var = "hello world"
>> var.encoding.to_s           #=> "UTF-8"
>> var.force_encoding("GBK")   #=> "hello world"
>> var.encoding.to_s           #=> "GBK"

valid_encoding?

valid_encoding? → true or false

判斷編碼轉換的過程是否正確。換句話說,本來可能由於編碼轉換報錯的語句,如今不報錯,而是返回bool值。

"\xc2\xa1".force_encoding("UTF-8").valid_encoding?  #=> true
"\xc2".force_encoding("UTF-8").valid_encoding?      #=> false
"\x80".force_encoding("UTF-8").valid_encoding?      #=> false

start_with?和end_with?

start_with?([prefixes]+) → true or false
end_with?([suffixes]+) → true or false

若是字符串的前綴、後綴能匹配所給定的字符串或正則表達式,則返回true。

注意,只有start_with能使用正則表達式的方式來匹配前綴,end_with只能經過精確匹配的方式。

能夠給多個前綴、後綴參數,表示任意一個知足條件便可。

例如:

# 精確匹配前綴、後綴
"hello".start_with?("hell")      #=> true
"hello".end_with?("ello")        #=> true

# 正則方式匹配前綴
"hello".start_with?(/H/i)        #=> true

# 多個前綴、後綴匹配
"hello".start_with?("heaven", "hell")     #=> true
"hello".start_with?("heaven", "paradise") #=> false
"hello".end_with?("heaven", "ello")     #=> true
"hello".end_with?("heaven", "paradise") #=> false

getbyte和setbyte

getbyte(index) → 0 .. 255
setbyte(index, integer) → integer

獲取或設置字符串中某個字節的byte值(一個整數值)。

>> var="hello"
>> var.bytes        #=> [104, 101, 108, 108, 111]
>> var.getbyte(1)   #=> 101

>> "我".bytes       #=> [230, 136, 145]
>> "我".getbyte(1)  #=> 136

gsub和gsub!

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

gsub!(pattern, replacement) → str or nil
gsub!(pattern, hash) → str or nil
gsub!(pattern) {|match| block } → str or nil
gsub!(pattern) → an_enumerator

gsub用來作字符串替換。

pattern部分是正則表達式對象,但也能夠是雙引號包圍的正則字符串,但不建議。因此,應該聽從使用/pattern/的方式做爲pattern參數的格式。

replacement表示要替換被pattern所匹配的內容。在replacement中,可使用反向引用\N、分組捕獲的分組引用\k<NAME>。replacement部分能夠是雙引號包圍的,也能夠是單引號包圍的字符串,若是是雙引號包圍的,那麼其中的反斜線要多加一個前綴\轉義。

使用hash參數時,表示pattern匹配的內容是hash中的某個key,那麼將根據hash中的key來對應替換。

使用語句塊時,將傳遞所匹配的內容到代碼塊中,這時會自動設置好$1, $2, $, $&, $'等變量。

對於gsub!,若是沒有作任何替換,則返回nil。

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

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

match()的pattern能夠是正則對象,也能夠是字符串,若是是字符串將轉換成正則表達式對象。

而後用pattern去匹配字符串,將匹配的內容放進MatchData類中,這個類中是對全部匹配到內容的封裝。

指定了pos後,表示今後位置處開始向後搜索。

若是match()後給了代碼塊,則將MatchData傳遞給代碼塊。

match?在匹配到內容時返回true,不然返回false。

'hello'.match('(.)\1')      #=> #<MatchData "ll" 1:"l">
'hello'.match('(.)\1')[0]   #=> "ll"
'hello'.match('(.)\1')[1]   #=> "l"
'hello'.match(/(.)\1/)[0]   #=> "ll"
'hello'.match(/(.)\1/, 3)   #=> nil
'hello'.match('xx')         #=> nil

'hello'.match('(.)\1') {|x| p x}  #=> #<MatchData "ll" 1:"l">

"Ruby".match?(/R.../)    #=> true
"Ruby".match?(/R.../, 1) #=> false
"Ruby".match?(/P.../)    #=> false
$&                       #=> nil

next和next!

succ和succ!

next → new_str
next! → str

succ → new_str
succ! → str

next和succ等價。

將字符串最右邊的字母/數組(不是最右邊的字符,由於最右邊的字符可能不是字母、數值)轉換成它的下一個位。例如最右邊的字符8變成9,a變成b。

須要注意:

  1. 數值和字母的遞增很容易理解。但若是徹底沒有字母、數值,則最右邊的字符按照排序規則進行遞增
  2. 若是發生了進位操做,則返回到左邊進行遞增。這是遞歸的,直到沒有可進位的操做爲止。在進位的時候,有可能會增長一個字符。看下面的示例
"abcd".succ        #=> "abce"      # 最後一個字母
"THX1138".succ     #=> "THX1139"   # 最後一個數值
"<<koala>>".succ   #=> "<<koalb>>" # 最後一個字母
">>>".succ         #=> ">>?"       # 沒有數值、字母,遞增最後一個字符
"1999zzz".succ     #=> "2000aaa"   # 先遞增zzz爲aaa,進位後遞增1999爲2000
"ZZZ9999".succ     #=> "AAAA0000"  # 先遞增9999爲0000,進位後遞增ZZZ爲AAAA
"***".succ         #=> "**+"       # 沒有數值、字母,遞增最後一個字符

partition和rpartition

partition(sep) → [head, sep, tail]
partition(regexp) → [head, match, tail]

rpartition(sep) → [head, sep, tail]
rpartition(regexp) → [head, match, tail]

從左或從右開始匹配字符串,並將第一次匹配以前的內容、第一次匹配的內容、第一次匹配以後的內容這三部分組成一個數組。

"hello".partition("l")         #=> ["he", "l", "lo"]
"hello".partition("x")         #=> ["hello", "", ""]
"hello".partition(/.l/)        #=> ["h", "el", "lo"]

"hello".rpartition("l")         #=> ["hel", "l", "o"]
"hello".rpartition("x")         #=> ["", "", "hello"]
"hello".rpartition(/.l/)        #=> ["he", "ll", "o"]

reverse和reverse!

reverse → new_str
reverse! → str

將字符串字符反轉。

"hello".reverse   #=> "olleh"

scan

scan(pattern) → array
scan(pattern) {|match, ...| block } → str

按照正則表達式匹配字符串,從前向後每次匹配到的結果放進數組或傳遞到代碼塊。

若是沒有使用分組捕獲,則從前向後每次匹配到的內容都做爲數組的元素或直接傳遞給代碼塊。

若是使用了分組捕獲,則正則每次匹配的分組放進子數組中。

a = "cruel world"
a.scan(/\w+/)        #=> ["cruel", "world"]
a.scan(/.l/)         #=> ["el", "rl"]
a.scan(/.../)        #=> ["cru", "el ", "wor"]
a.scan(/(...)/)      #=> [["cru"], ["el "], ["wor"]]
a.scan(/(..)(..)/)   #=> [["cr", "ue"], ["l ", "wo"]]


a.scan(/\w+/) {|w| print "<<#{w}>> " }
   #=> <<cruel>> <<world>>
a.scan(/(.)(.)/) {|x,y| print 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的最後一個字符填充到to_str的尾部以便達到和from_str相同的長度進行一一映射。

# 如下兩條語句等價
"hello".tr('aeiou', '*')    #=> "h*ll*"
"hello".tr('aeiou', "*****")#=> "h*ll*"

# 如下兩條語句等價
"hello".tr('aeiou', 'AA*')    #=> "hAll*"
"hello".tr('aeiou', 'AA***')  #=> "hAll*"

from_str和to_str均可以使用-表示範圍,例如0-9a-d等。

在from_str中還可使用^表示除了這些字符,其它都替換,即從字符串中取反。所替換的目標字符串爲to_str的最後一個字符。

"hello".tr('a-y', 'b-z')    #=> "ifmmp"
"hello".tr('^aeiou', '*')   #=> "*e**o" 
    # 上面第二條表示hello中除了aeiou,其它字母即h和l都替換

"hello".tr('^aeiou', '123457') #=> "7e77o"

tr_s和tr_s!

tr_s(from_str, to_str) → new_str
tr_s!(from_str, to_str) → str or nil

在進行tr替換後,壓縮替換部分連續相同的字符。注意,非替換部分的字符不計入考慮。

"hello".tr_s('l', 'r')     #=> "hero"
"hello".tr_s('el', '*')    #=> "h*o"
"hello".tr_s('el', 'hx')   #=> "hhxo"
相關文章
相關標籤/搜索