最近因為公司需求開始看ruby,先從ruby的基本數據類型開始看
看到ruby的字符串類型string,發現ruby中的字符串單雙引號是不一樣的,這點和Python有那么點不一樣
主要是我們對字符串進行變量引用的時候要使用雙引號
如下:
可支持全部的轉義字符及用#{exp}將Ruby中的值插入字符串中
例:
i = 5
str = “ abab#{i}cjd” #->abab5cjd
“#{‘ho‘ *3} happy new year” #->ho ho ho happy new year
這是最大的區別
現在來看看ruby中字符串的方法:
1. 遇到\會進行轉義
2.2.1 :041 > puts "daad\'" daad' => nil 2.2.1 :042 > puts "daad\\" daad\ => nil
2. + 可以將字符串連接起來
例:
2.2.1 :043 > 'abc'+'def' => "abcdef"
3. 字符串的內容重復times次
例:
2.2.1 :043 > 'abc'+'def' => "abcdef"
4. 返回字符串的長度
length,size
例:
2.2.1 :052 > str = "123456789" => "123456789" 2.2.1 :054 > str.length => 9 2.2.1 :055 > str.size => 9
5.判斷字符串中是否包含另一個字符串
str.include? other_str => true or false
例:
2.2.1 :060 > 'ruby'.include?'ru' => true 2.2.1 :061 > 'ruby'.include?'pp' => false
6.字符串的插入
str.insert(index, other_str)=> str
2.2.1 :062 > 'ruby'.insert(0,'add') # 在索引為0的位置插入a,索引從0開始 => "addruby" 2.2.1 :063 > 'ruby'.insert(-1,'add') #從最后一個索引開始添加 => "rubyadd"
7.字符串分割,默認分隔符為空格
str.split(pattern=$;, [limit]) =>anArray
和python差不多
例:
2.2.1 :065 > 'ruby abc def'.split # 默認是一個空格符 => ["ruby", "abc", "def"] 2.2.1 :066 > 'ruby abc def'.split('a') => ["ruby ", "bc def"] 2.2.1 :067 > 'ruby abc def'.split('',4) => ["r", "u", "b", "y abc def"] 2.2.1 :068 > 'ruby abc def'.split(' ',4) => ["ruby", "abc", "def"]
8.字符串的替換
str.sub(pattern, replace) str.gsub(pattern, replace)
str.sub!(pattern, replace) str.gsub!(pattern, replace)
str.sub(pattern) {|matched| ... } str.gsub(pattern){|matched| ... }
str.sub!(pattern) {|matched| ...} str.gsub!(pattern){|matched| ... }
str.replace(other_str)=> str # replace來替換整個str,str本身也被改變。
sub生成並返回替換后的字符串。而sub!會修改str本身並返回結果。若沒有進行替換時返回nil。sub只替換第一次匹配的部分,gsub替換所有匹配的部分。
例如:
str = “hello”
str.sub(/[aeiou]/, '*') #->"h*llo" # str = “hello”
str.sub!(/[aeiou]/, '*') #->"h*llo" # str = "h*llo"
str.gsub(/[aeiou]/, '*') #-> "h*ll*" #將元音替換成*號
str.gsub(/./){|s| s[0]+’ ‘} #-> "h e l l l o" #將所有元素后加空格
str.replace(“he”) #->”he” #str=” he”
9、 字符串刪除
str.delete([other_str]+) => new_str #刪除參數交集出現的所有字符,返回一個新字符串
str. delete! ([other_str]+) => str #原字符串會被改變
2.2.1 :078 > 'hello'.delete 'l' => "heo" 2.2.1 :079 > 'hello'.delete 'l','lo' => "heo" 2.2.1 :080 > 'hello'.delete 'lo' => "he"
10. 去掉空白
str. strip => new_str #刪除頭部和尾部的空白
str.strip! =>str #刪除頭部和尾部的空白,原字符串本身被改變,若無刪除動作,則返回nil,str本身不變
str.lstrip => new_str #刪除頭部的空白
str. lstrip !=> str #刪除頭部的空白,原字符串本身被改變,若頭部無空白,則返回nil,str本身不變
str.rstrip => new_str #刪除尾部的空白
str.rstrip !=> str #刪除尾部的空白,原字符串本身被改變,若尾部無空白,則返回nil,str本身不變
例:
p " abc\n".lstrip #=>"abc\n"
p "\t abc\n".lstrip #=> "abc\n"
p "abc\n".lstrip #=> "abc\n"
str = "\nabc"
p str.lstrip #=>"abc"
p str #=>"\nabc" (無變化)
str = " abc"
p str.lstrip! #=>"abc"
p str #=>"abc" (有變化)
str = "abc"
p str.lstrip! #=>nil
p str #=>"abc"
11.字符串匹配
str.match(pattern)=> matchdata or nil
例:
2.2.1 :093 > 'hello'.match(/l+/)
=> #<MatchData "ll">
2.2.1 :094 > 'hello'.match(/\w+/)
=> #<MatchData "hello">
12.字符串反轉
str.reverse => new_str
str.reverse! => str # str本身會發生改變
2.2.1 :095 > 'hello'.reverse => "olleh"
13.去掉重復的字符
str.squeeze([other_str]*) => new_str
str.squeeze!([other_str]*) => str #str本身被改變,若無刪除動作,返回nil,
str不變
例:
"hello moon".squeeze #=> "helo mon" #默認去掉串中所有重復的字符
" hello moon ".squeeze(" ") #=> " hello moon " #去掉串中重復的空格
" hello moon”. squeeze ("m-z") #=> " hello mon " #去掉指定范圍內的重復字符
14、字符串轉化為數字
to_f:將字符串看作是10進制數形式,並將其變為浮點數Float。將不能被看作浮點數的那個部分之前的內容變為浮點數。若變換對象是空字符串則返回 0.0 。
例:
p "10".to_f #=> 10.0
p "10e2".to_f #=> 1000.0
p "e2".to_f # =>0.0 #頭部第一個字符不可被看作浮點數
p "1e-2".to_f #=> 0.01
p ".1".to_f #=> 0.1
p " \n10".to_f # => 10.0 # 頭部的空白被忽略
p "1_0_0".to_f # => 100.0 # `_' 被忽略
p "".to_f #=> 0.0
to_i:將字符串看作是10進制數形式,並將其變為整數。若遇到不能變為整數的字符,就將它前面的內容變為整數。若變換對象為空字符串,則返回0。
例:
p " 10".to_i #=> 10
p " 10e2".to_i #=> 10
p "1e-2".to_f #=> 1
p "010".to_i #=> 10
p "-010".to_i #=> -10
p "0x11".to_i #=> 0
p ".1".to_i # =>0
to_i(base) :通過指定不同的基數,還可以進行2~36進制的轉換。若指定為0時,則通過 prefix 來判斷基數(相反地,只有將其指定為0時,才會識別prefix)。若使用了0、2~36之外的參數時,會引發ArgumentError異常。
例:
p "0b10".to_i(0) #=> 2
p "0b10".to_i(2) #=> 2
p "0o10".to_i(0) # => 8
p "010".to_i(0) #=> 8
p "0d10".to_i(0) #=> 10
p "0d10".to_i(8) #=> 0
p "0x10".to_i(0) #=> 16
15、 刪除字符串最后的字符
str.chop :刪除字符串str的最后一個字符,並返回新字符串
#若字符串以\r\n結尾,則兩個字符都刪去
#若字符串為空串,則返回空串
str.chop !:修改str本身並返回結果,若沒做修改,則返回nil。
例:
"string\r\n".chop #->"string"
"string\n\r".chop #->"string\n"
"string".chop #->"strin"
"s".chop.chop #->""
str.chomp(endstr) :刪除str的后綴endstr,如果未指定endstr,則刪除回車換行符(\r、\n和\r\n);若endstr的取值是nil的話,將不作任何的動作。
str.chomp!(endstr) :修改str本身並返回結果,若沒做修改,則返回nil。
例:
"hello\r\n".chomp #->"hello"
"hello".chomp("lo") #->"hel"
"hello".chomp("l") #->nil
16、 格式化字符串
arg為數組時,使用sprintf(self,*args)
arg為非數組時,使用sprintf(self,args)
例:
name = "Bob"
age = 28
str = sprintf("Hi, %s... I see you're %d years old.", name, age) #->”Hi, Bob... I see you're 28
years old”
格式 字符串
例:
p "%#x" % 10 # => "0xa"
p "%#x,%#o" % [10, 10] # => "0xa,012"
str.center(width)
str.ljust(width)
str.rjust(width)
str.center(width[,padding])
str.ljust(width[,padding])
str.rjust(width[,padding])
分別返回居中、靠左、靠右的字符串,當字符串長度超過width時,將返回原字符串的拷貝;若使用了第二參數padding的話,將使用padding來填充空白。
例:
str = "Moby-Dick"
s1 = str.ljust(13) #"Moby-Dick "
s2 = str.center(13) #" Moby-Dick "
s3 = str.rjust(13) #" Moby-Dick"
s4 = str.rjust(13,'*') #"****Moby-Dick"
str.center(1).id== str.id # => false #返回原字符串的拷貝
17. 控制字符串的大小寫
str.capitalize:將首字符(若為字母的話)改為大寫字母,其余的改為小寫字母,生成並返回
修改后的字符串。。
str.capitalize!:會修改str本身並返回結果,若未作修改時返回nil。
例:
"foobar".capitalize # => "Foobar"
str.downcase:將字符串中的大寫字母都改為小寫字母,生成並返回修改后的字符串
str.downcase!:會修改str本身並返回結果,若沒有作修改,則返回nil.
str.upcase:將字符串中的小寫字母都改為大寫字母,生成並返回修改后的字符串
str.upcase!:會修改str本身並返回結果,若沒有作修改,則返回nil.
str. swapcase:將所有的大寫字母改為小寫字母,小寫字母改為大寫字母,生成並返回
修改后的字符串
str. swapcase!:會修改str本身並返回結果,若沒有作修改,則返回nil.
例:
s = "Hello,World"
s.downcase #"hello,world"
s.upcase #"HELLO,WORLD"
s.swapcase #"hELLO,wORLD"
18.字符串的匹配
“=~”:與正則表達式的匹配
例:
if string =~ /[a-z]/ #檢查字符串中是否有小寫字符
puts "string contains lowercase charcters"
end
if string =~ /[A-Z]/ #檢查字符串中是否有大寫字符
puts "string contains uppercase charcters"
end
if string =~ /[A-Z]/ and string =~ /a-z/ #檢查字符串中是否既有大寫又有小寫字符
puts "string contains mixed case"
end
if string[0..0] =~ /[A-Z]/ #檢查字符串中第一個字符是否大寫
puts "string starts with a capital letter"
end
p “AhdhBBN”=~/[A-Z]/ 返回0
字符串與正則相關的方法還有match和scan,match返回第一個匹配對象,scan返回所有符合正則表達式的數組
例:
“hello”.match(/[a-h]/) #<MatchData “h”>
“hello”.scan(/[a-h]/) #[“h”,”e”]
19.字符串的子串
str[num1,num2]:num1代表取字符串的偏移位置,num2表示取的長度,其中num1可以是負數:
例:
str = "Humpty Dumpty"
sub1 = str[7,4] # "Dump"
sub2 = str[7,99] # "Dumpty" (超過的長度按實際長度來取)
sub3 = str[10,-4] # nil (長度為負數了)
str1 = "Alice"
sub1 = str1[-3,3] # "ice"
str2 = "Through the Looking-Glass"
sub3 = str2[-13,4] # "Look"
Range取子串:利用腳標取子串
例:
str = "Winston Churchill"
sub1 = str[8..13] # "Church"
sub2 = str[-4..-1] # "hill"
sub3 = str[-1..-4] # “”
sub4 = str[25..30] # nil
str = "Alistair Cooke"
sub1 = str[/l..t/] # "list"
sub2 = str[/s.*r/] # "stair"
sub3 = str[/foo/] # nil
如果給出的是一個字符串,則如果目標字符串中含有這個給出的字符串,則返回這個給出的字符串,否則返回nil:
str = "theater"
sub1 = str["heat"] # "heat"
sub2 = str["eat"] # "eat"
sub3 = str["ate"] # "ate"
sub4 = str["beat"] # nil
sub5 = str["cheat"] # nil
如果給出的是一個數字,則返回的是該數字對應索引處字符的ASCII碼:
str = "Aaron Burr"
ch1 = str[0] #A
ch1 = str[1] #a
ch3 = str[99] # nil
[v1]返回匹配正則表達式中的第一個字符的位數,p “ssD”=~/[A-Z]/ 返回2