On 12 Mar, 16:25, "Rick DeNatale" <rick.denat... / gmail.com> wrote:
> On 3/12/07, Robert Klemme <shortcut... / googlemail.com> 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 thestring. 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 inputstring, 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'.
>
> classString
>   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 Rubyhttp://talklikeaduck.denhaven2.com/

Being new to Ruby thats a great piece of code to get my head around,
thanks all for suggestions thoughts and ideas :)