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处理空白字符
移除开头和结尾空白字符
" Whitespace at beginning and end. ".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