Quick and dirty word wrapping

Hmm, nice, just one little thing:

str = '12345678901234567890'
puts str.wrap_to( 10 )
puts
puts str.wrap_to( 5 )

output:

1234567890
1234567890

12345
78901
34567
890

it 'eats' chars...

cheers

Simon

···

-----Original Message-----
From: Gavin Kistner [mailto:gavin@refinery.com]
Sent: Wednesday, September 14, 2005 4:47 PM
To: ruby-talk ML
Subject: Re: Quick and dirty word wrapping.

On Sep 14, 2005, at 8:39 AM, Gavin Kistner wrote:
> On Sep 14, 2005, at 8:26 AM, Erik Terpstra wrote:
>
>> str = 'This is a test of the emergency broadcasting services'
>> str.scan(/(.{1,30})(?:\s+|$)/)
>>
>> => [["This is a test of the"], ["emergency broadcasting"],
>> ["services"]]
>>
>
> Nice. Not to golf, but how about simply:
>
> str = 'This is a test of the emergency broadcasting services'
> p str.scan(/.{1,30}\b/)
> #=> ["This is a test of the ", "emergency broadcasting ",
"services"]

Oops, because mine will split punctuation from its characters.
However, both of ours will lose lines that are \S{31,}

So:

str = '123456789012345678901234567890This is a test of the emergency
broadcasting system. This is only a test.'

class String
     def wrap_to( col_width )
         str = self.gsub( /(\S{#{col_width}})(\S)/, '\1 \2' )
         str.scan(/(.{1,#{col_width}})(?:\s+|$)/).flatten.join( "\n" )
     end
end

puts str.wrap_to( 30 )
123456789012345678901234567890
[..snip..]

Hmmm.... Here is my quick fix for him ...

class String
    def wrap_to( col_width )
        str = self.gsub( /(\S{#{col_width}})(?=\S)/, '\1 ' )
        str.scan(/(.{1,#{col_width}})(?:\s+|$)/).flatten.join( "\n" )
    end
end

"Kroeger Simon (ext)" <simon.kroeger.ext@siemens.com> wrote in message

it 'eats' chars...

Yup. Lost the "b" in "b"roadcasting below.

irb(main):007:0> str.scan(/(.{1,10})(?:\s+|$)/)
=> [["This is a"], ["test of"], ["the"], ["emergency"], ["oadcasting"],
["services"]]

The origin post assumes no word longer then wrap size.
So if you like the wrap size less than word length, you have to change
a little bit regexp.

Here is my change to make sure no lost char ...

str = 'This is a test of the emergency broadcasting services'
p str.scan(/(.{1,10}|\S{11,})(?:\s+|$)/) # for wrap size == 10
# => [["This is a"], ["test of"], ["the"], ["emergency"],
["broadcasting"], ["services"]]

p str.scan(/(.{1,5}|\S{6,})(?:\s+|$)/) # for wrap size == 5
# => [["This"], ["is a"], ["test"], ["of"], ["the"], ["emergency"],
["broadcasting"], ["services"]]