Word Wrapping at n characters

Right now I basically use this code for word wrapping:

def word_wrap(line_width = 80)
self.gsub(/(.{1,#{line_width}})(\s+|$)/, “\1\n”)
end

Is anyone using a better solution? This method should be
robust enough to do “proper” line wrapping of really
long strings - like strings long enough to fill
a big book.

Here is an alternative with analysis and comments:

http://blog.macromates.com/2006/wrapping-text-with-regular-expressions/

The code looks like this:

def wrap_text(txt, col = 80)
txt.gsub(/(.{1,#{col}})( +|$\n?)|(.{1,#{col}})/,
“\1\3\n”)
end

regards,
Tor Erik
http://tel.jklm.no/

7stud – wrote:

str =<<EOS
hello hello hello hello hello hello hello hello hello hello hello hello
hello hello
goodbye goodbye goodbye goodbye
EOS

Note all the hello’s were on one line.

–output:–
hello hello hello hello hello hello hello hello hello hello hello hello
hello
hello
goodbye goodbye goodbye goodbye

The output is really:

line #1: hello’s
line #2: one hello
line #3: goodbye’s

Marc H. wrote:

Right now I basically use this code for word wrapping:

def word_wrap(line_width = 80)
self.gsub(/(.{1,#{line_width}})(\s+|$)/, “\1\n”)
end

Is anyone using a better solution? This method should be
robust enough to do “proper” line wrapping of really
long strings - like strings long enough to fill
a big book.

str =<<EOS
hello hello hello hello hello hello hello hello hello hello hello hello
hello hello
goodbye goodbye goodbye goodbye
EOS

class String
def word_wrap(line_width = 80)
self.gsub(/(.{1,#{line_width}})(\s+|$)/, “\1\n”)
end
end

puts str.word_wrap

–output:–
hello hello hello hello hello hello hello hello hello hello hello hello
hello
hello
goodbye goodbye goodbye goodbye

Is that what you want?