Word Wrapping at n characters

M

Marc Heiler

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.
 
7

7stud --

Marc said:
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?
 
7

7stud --

7stud said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top