From: Rick DeNatale Date: 2007-03-13T01:25:14+09:00 Subject: Re: Efficiency of string parsing On 3/12/07, Robert Klemme wrote: > There are quite a lot of posts about word wrapping which seems what you > are trying to do. You should be able to find them via the archives > (Google Groups, ruby-talk archive). > > A simplistic approach would probably do something like this: > > str.gsub(/(.{1,50})\s+/, "\\1\n") > And here's the start of a more sophisticated approach I just whipped up. It uses split on a word boundary to split the string. It has some option keywords which allow preserving all whitespace, or only at the beginning of a line. If you don't preserve all whitespace, it collapses whitespace within a line to a single space. If you don't preserve whitespace at the beginning of a line, it elminates it, otherwise it keeps it as is. The default is to only preserve whitespace at the beginning of a line. It does have a few bugs, which I didn't bother addressing and leave as an exercise ot the reader. 1) It ignores existing new lines in the input string, which means that the next line will be short. 2) It keeps whitespace at the end of a line, as opposed to putting the newline after the last 'word'. class String def wordwrap(linelength, kw_args={}) keep_all = kw_args[:keep_all] keep_initial = keep_all ||kw_args[:keep_initial] keep_initial = true if keep_initial.nil? current_len = 0 split(/\b/).inject("") do | result, chunk | if current_len + chunk.length >= linelength result << "\n" current_len = 0 chunk = "" if chunk.strip.empty? unless keep_initial else chunk = " " if chunk.strip.empty? unless keep_all end current_len += chunk.length result << chunk end end end -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/