1 單獨處理字串的字元
如果處理的是ASCII碼的文件使用string#each_byte
注意 沒有 string#each方法,String#each_byte 速度比 String#scan快 ,String#scan用於配合正規表示式時使用
'foobar'.each_byte { |x| puts "#{x} = #{x.chr}" } # 102 = f # 111 = o # 111 = o # 98 = b # 97 = a # 114 = r
'foobar'.scan( /./ ) { |c| puts c } # f # o # o # b # a # r
2 分割一段文字。並對每個單詞進行處理
class String def word_count frequencies = Hash.new(0) downcase.scan(/\w+/) { |word| frequencies[word] += 1 } frequencies end end p %{Dogs dogs dog dog dogs.}.word_count
3 字串大小寫轉換
s = 'HELLO, I am not here , I WENT to tHe MaRKEt' p s.upcase # "HELLO, I AM NOT HERE , I WENT TO THE MARKET" p s.downcase # "hello, i am not here , i went to the market" p s.swapcase # "hello, i AM NOT HERE , i went TO ThE mArkeT" p s.capitalize # "Hello, i am not here , i went to the market"
s = "abc" p s.tr('a','A')
4處理空白字元
移除開頭和結尾空白字元
" \tWhitespace at beginning and end. \t\n\n".strip # => "Whitespace at beginning and end."
移除一端的空格
s = " Whitespace madness! " s.lstrip # => "Whitespace madness! " s.rstrip # => " Whitespace madness!"
5 判斷一個物件可否作為字串
判斷物件是否有to_str方法
'A string'.respond_to? :to_str # => true Exception.new.respond_to? :to_str # => true 4.respond_to? :to_str # => false