Section 2.40. Wrapping Lines of Text


2.39. Expanding and Compressing Tab Characters

Occasionally we have a string with tabs in it and we want to convert them to spaces (or vice versa). The two methods shown here do these operations.

class String   def detab(ts=8)     str = self.dup     while (leftmost = str.index("\t")) != nil       space = " "*(ts-(leftmost%ts))       str[leftmost]=space     end     str   end   def entab(ts=8)     str = self.detab     areas = str.length/ts     newstr = ""     for a in 0..areas       temp = str[a*ts..a*ts+ts-1]       if temp.size==ts         if temp =~ / +/           match=Regexp.last_match[0]           endmatch = Regexp.new(match+"$")           if match.length>1             temp.sub!(endmatch,"\t")           end         end       end       newstr += temp     end     newstr   end end foo = "This       is        only   a     test.          " puts foo puts foo.entab(4) puts foo.entab(4).dump


Note that this code is not smart enough to handle backspaces.




The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net