Word wrapping.

L

listrecv

Is there a simple way to use Ruby to wrap a long string to a set
interval, on whitespace?

IE - take String x, and break it up on whitespace boundaries, so that
no col is over L chars (bytes in Ruby :-( ) long?

I'm not sure if it would be better to convert spaces to newlines, or to
just add the newline after the space. (Any ideas?)

Also, newlines, tabs, multiple spaces, etc. should be preserved.
 
L

listrecv

Wow! Not bad - only 12 minutes later, and your response itself is on
the Google search page. Talk about quick indexing!

Thanks for the tip.
 
J

James H.

Naively...

1. Read the string.
2. Slice the string on spaces
words = string.split(/ /)
3. Construct a new output string
words.each {|word| output_string.concat("#{word} ") if
(output_string.length + word.length) < MAX_LENGTH
4. Print out the new line

How's that work?

James H
 
L

listrecv

In case anyone's interested:

require 'rubygems'
require_gem 'text-format'

formatter = Text::Format.new
formatter.columns = ARGV[0] || 76
formatter.first_indent = 0 # Don't tab new paragraphs

puts formatter.paragraphs(STDIN.read)
 
I

ian k.

In case anyone's interested:

require 'rubygems'
require_gem 'text-format'

formatter = Text::Format.new
formatter.columns = ARGV[0] || 76
formatter.first_indent = 0 # Don't tab new paragraphs

puts formatter.paragraphs(STDIN.read)

you could also use the unix fmt utility:
`fmt -w 72`

not sure if it's quicker.
 

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,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top