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
endputs str.wrap_to( 30 )
123456789012345678901234567890
[..snip..]