From: Ara.T.Howard@... Date: 2005-04-29T02:24:29+09:00 Subject: Re: string#fmt - breaking lines (no indent) On Fri, 29 Apr 2005, Josef 'Jupp' SCHUGT wrote: > Hi! > > After some trouble with mail programs not supporting "format=flowed" I > wrote a quick hack that line-breaks strings but keeps words intact > that exceed the intended line-length (currently hard-wired to 72 - I > already wrote that it is a quick hack, didn't I?). No warranty of any > kind. Improvements welcome. I did not forget to implement indentations > - the strings that I apply String#fmt to simply don't have them. > > class String > def fmt > maxlen = 72 > result = "" > temp = "" > gsub(/[ \s]+/, ' ').strip.scan(/[^ ]+/) { |x| > if temp == "" > temp << x > else > if temp.length + x.length < maxlen > temp << " " + x > else > result << temp + "\n" > temp = "" > redo > end > end > } > result + temp > end > end for anyone wanting to make a really robust version i'm contributing my code to do the same too: module Util # # wrap a string using options width (default 80) and indent using the indent # option (default 0) # def columnize buf, opts = {} #--{{{ width = getopt 'width', opts, 80 indent = getopt 'indent', opts, 0 columns = [] words = buf.split %r/\s+/o row = ' ' * indent while((word = words.shift)) if((row.size + word.size) < (width - 1)) row << word else columns << row row = ' ' * indent row << word end row << ' ' unless row.size == (width - 1) end columns << row unless row.strip.empty? columns.join "\n" #--}}} end # # look up key in hash as key, then string of key, then intern of key - # returning the value or, if key is not found, nil or default # def getopt opt, hash, default = nil #--{{{ key = opt return hash[key] if hash.has_key? key key = "#{ key }" return hash[key] if hash.has_key? key key = key.intern return hash[key] if hash.has_key? key return default #--}}} end end improvements welcome. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | renunciation is not getting rid of the things of this world, but accepting | that they pass away. --aitken roshi ===============================================================================