luke schrieb:
> ideally how i would like it to behave given your examples, would be like:
> 
> "abcde\n  c".wrap(5)  # => "abcde\nc"
> "a   e\na".wrap(5)    # => "a   e\na"
> 
> does that make sense? so text would be flush with the left margin with no
> white space at the beginning of new lines. but whitespace within a line
> should remain intact.

Of course it makes sense. Here's one version:

   class String
     def wrap n
       gsub(
         /
           \b           # word boundary
           [ \t\r\f]*   # whitespace (no newline)
           \n           # newline
           [ \t\r\f]*   # whitespace (no newline)
           \b           # word boundary
         /x,
         " "            # replaced by space
       ).gsub(
         /
           (.{1,#{n}})  # upto n characters
           (            # followed by either:
             \n         #   exactly one newline
             |\s+       #   or other whitespace characters
           )
         /x,
         "\\1\n"        # insert newline after first part
       )
     end
   end

I used extended regular expressions to show what they are doing. You can 
shorten them if you want.

The first gsub replaces newlines inside of paragraphs into spaces, but 
leaves newlines between paragraphs unchanged. The second gsub is mostly 
the original one, but it consumes at most one newline character 
(replacing it with itself). This has the effect that newlines between 
paragraphs are preserved.

If you still have problems or questions, feel free to ask.

Regards,
Pit