2008年4月30日 星期三

string method


crate string array

ex:

%w[AB CD]

---> [“AB”, “CD”]


gsub & gsub!:

global substitution 

ex:

"hello".gsub("e","a")

--->  "hallo"

gsub! will change original string


gsub & sub:

gsub change every match, sub only change first match

ex:

"helleo".gsub("e","a")

--> "hallao"

"helleo".sub("e","a")

--> "halleo"


sprintf:

ex:  

sprintf(“%2d”, 3)

--> “  3”


inject:

ex:

[1, 2,3].inject(10) {  | sum, number|  sum=sum+number }

--> 16

inject初始sum為10,

然後10+1=11

11+2=13

13+3=16


chomp:

remove the newline character


chop:

remove last character 


grep:

ex:

["test", "b", "testa", "test"].grep("test")

--->["test", "test"]


split:

ex:  

“hello”.split(‘e’)

 --->["h", "llo"]

ex:   

a, b= "hello".split('e')

--> a= "h", b="llo"


chr:

a= "abcde"

a[0].chr

-->  "a"


strip:

return a copy with leading and tailing whitespace removed


lstrip & rstrip

removing left or right whitespace 


%q :

create string, single-quoted

ex:

%q (abc)

---> "abc"


%Q: 

create string, double-quoted 


\ :

use \ to escape:

ex:

puts "abc\"de"

--->  abc"de


<<:

add string(modify original string)

ex:

a="test"

a<< "abc:

puts a

-->  testabc


replace:

ex:

a="test"

a.replace("abc")

puts a

---> abc


reverse,  downcase, upcase, capitalize, swapcase 


substring:

ex:

"abcde"[2,2]

--->  "cd"

a="abcde"

a[2,2]="gg"

a

---> "abgge"


succ:

ex:

"abc".succ

--> "abb"


%:

format string

ex:

"%.2f"%3.333

--->"3.33"

沒有留言: