From: Ian Hobson Date: 2010-06-03T18:57:33+09:00 Subject: Re: Split text into equal characters but keeping whole words On 03/06/10 10:19, John Butler wrote: > Hi, > > I have text that is petty large. What i want to do is split it into an > array of no more than 250 characters per line but finishing on a full > word at the end of each line. So if the last word was "ruby" but 'b' > was the 250th character in the line then i want the line to cut off > before ruby and then start at ruby for the next line. What i have at > the minute is below which splits the text into an array of lines 250 > characters long, but as i say it slices through words at the end of the > 250 character limit. > > mytext.scan(/.{1,250}/m) > > This is a remarkably subtle problem. The key is to read the input a "word" at a time, and pack words into the output only if there is room on the current line. A word break is any newline or whitespace - see below. Issues to consider: What if the input has a word longer than the output line? Should it be split? What if the input has multiple spaces? Should they be preserved or collapsed into one? What about paragraph breaks? Regards Ian