On 10/3/05, Mark J. Reed <mreed / thereeds.org> wrote:
> Mark J. Reed <mreed / thereeds.org> writes:
>
> >    while words do
> >        line = '//   '
> >        while words && line.length < 78 do
> >           line += words.shift + ' '
> >       end
> >       puts line
> >    end

Thanks to e all who replied.  I took Ara's idea to make it generic,
and the basic look from Mark, and this is what I came up with:

def TextWrap(lines, prefix = '', postfix = '', wrapat = 78, rightAlign = nil)
  if prefix.size + postfix.size > wrapat then
    raise RuntimeError, "prefix length + postfix length > wrapat"
  end
  wrapped = []
  words = lines.split(/\s+/)
  while words.size > 0 do
    line = prefix
    if (words[0].length + prefix.length + postfix.length) > wrapat then
      # A single long word can cause problems
      line += words.shift
    else
      while (words.size > 0) &&
            ((line.length + words[0].length + postfix.length) <= wrapat) do
        line += words.shift + ' '
      end
    end
    if rightAlign then
      padlength = wrapat - (line.length + postfix.length)
      line += " " * padlength if padlength > 0
    end
    line += postfix
    wrapped << line
  end
  wrapped
end

It won't stand up to abuse, but it will do anything I need it to for a
while.  I made a couple changes from what you suggested, Mark.

I need to check against words.size, not just words since shifting all
the values out does not make the array nil.  Also, I added the word
length and the postfix length to the line length to make sure
everything will fit within the wrap boundary before adding the word. 
There is some ugliness to handle very long words.

Can it be prettied up?  I have avoided dynamic languages in the past
because my primary use for them is text processing, which I hate and
try not to think about.  :)

-Ben