整數有用的迭代器 3.times { print "X " } => X X X 1.upto(5) { |i| print i, " " } =>1 2 3 4 5 99.downto(95) { |i| print i, " " }=>99 98 97 96 9550.step(80, 5) { |i| print i, " " }=>50 55 60 65 70 75 80
二、字符串
Ruby的字符串是8位字節的簡單序列,字符串是String類的對象
注意轉換機制(注意單引號與雙引號的區別),如: 單引號中兩個相連的反斜線被替換成一個反斜線,,一個反斜線后跟一個單引號被替換成一個單引號 'escape using "//"' >> 轉義為"/" 'That/'s right' >> That's right
雙引號支持多義的轉義 "/n" #{expr}序列來替代任何的Ruby表達式的值 ,(全局變量、類變量或者實例變量,那么可以省略大括號) "Seconds/day: #{24*60*60}" >> Seconds/day: 86400 "#{'Ho! '*3}Merry Christmas" >> Ho! Ho! Ho! Merry Christmas "This is line #$." >> This is line 3
here document來創建一個字符串,end_of_string 為結束符號 aString = <<END_OF_STRINGThe body of the stringis the input lines up toone ending with the same text that followed the '<<'END_OF_STRING
%q和%Q分別把字符串分隔成單引號和雙引號字符串(即%q與%Q后面的符號具有',"的功能) %q/general single-quoted string/ >> general single-quoted string
用Regxp#match(aString)的形式或者匹配運算符=~(正匹配)和!~(負匹配)來匹配字符串了。匹配運算符在String和Regexp中都有定義,如果兩個操作數都是字符串,則右邊的那個要被轉換成正則表達式 exp: a = "Fats Waller" a =~ /a/ >> 1 a =~ /z/ >> nil a =~ "ll" >> 7
上面返回的是匹配字符的位置,其它 $&接受被模式匹配到的字符串部分 $`接受匹配之前的字符串部分 $'接受之后的字符串。 exp:下面的方法后繼都會用到 def showRE(a,re) if a =~ re "#{$`}<<#{$&}>>#{$'}" #返回前、中、后 else "no match" end end
字符類縮寫 序列 形如 [ ... ] 含義 /d [0-9] Digit character /D [^0-9] Nondigit /s [/s/t/r/n/f] Whitespace character 匹配一個單空白符 /S [^/s/t/r/n/f] Nonwhitespace character /w [A-Za-z0-9_] Word character /W [^A-Za-z0-9_] Nonword character
重復 r * 匹配0個或多個r的出現 r + 匹配一個或多個r的出現 r ? 匹配0個或1個r的出現 r {m,n} 匹配最少m最多n個r的出現 r {m,} 匹配最少m個r的出現
重復結構有高優先權:即它們僅和模式中的直接正則表達式前驅捆綁 /ab+/匹配一個"a"后跟一個活著多個"b",而不是"ab"的序列 /a*/會匹配任何字符串:0個或者多個"a"的任意字符串。 exp: a = "The moon is made of cheese" showRE(a, //w+/) >> <<The>> moon is made of cheese showRE(a, //s.*/s/) >> The<< moon is made of >>cheese showRE(a, //s.*?/s/) >> The<< moon >>is made of cheese showRE(a, /[aeiou]{2,99}/) >> The m<<oo>>n is made of cheese showRE(a, /mo?o/) >> The <<moo>>n is made of cheese
替換 "|"既匹配它前面的正則表達式或者匹配后面的 a = "red ball blue sky" showRE(a, /d|e/) >> r<<e>>d ball blue sky showRE(a, /al|lu/) >> red b<<al>>l blue sky showRE(a, /red ball|angry sky/) >> <<red ball>> blue sky
分組 圓括號把正則表達式分組,組中的內容被當作一個單獨的正則表達式 showRE('banana', /(an)+/) >> b<<anan>>a # 匹配重復的字母 showRE('He said "Hello"', /(/w)/1/) >> He said "He<<ll>>o" # 匹配重復的子字符串 showRE('Mississippi', /(/w+)/1/) >> M<<ississ>>ippi
基于模式的替換 你是否想過,大小寫替換。 方法String#sub和String#gsub都在字符串中搜索匹配第一個參數的部分,然后用第二個參數來替換它們。String#sub只替換一次,而String#gsub替換所有找到的匹配。都返回一個包含了替換的新的字符串的拷貝。進化版本是String#sub!和 String#gsub! a = "the quick brown fox" a.sub(/[aeiou]/, '*') >> "th* quick brown fox" a.gsub(/[aeiou]/, '*') >> "th* q**ck br*wn f*x" a.sub(//s/S+/, '') >> "the brown fox" a.gsub(//s/S+/, '') >> "the" 第二個參數可以是代碼塊 a = "the quick brown fox" a.sub (/^./) { $&.upcase } >> "The quick brown fox" a.gsub(/[aeiou]/) { $&.upcase } >> "thE qUIck brOwn fOx"