From: Gavin Kistner Date: 2005-09-15T10:00:47+09:00 Subject: Re: Quick and dirty word wrapping. On Sep 14, 2005, at 4:04 PM, David Tran wrote: > 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 Following feels like a good replacement for the existing Nano String#word_wrap method. Using gsub! (seen below) instead of scan.flatten.join (seen above) was a bit (but not much) faster. The non-destructive method can be re-written to be a hair faster by not relying on the destructive one, but it doesn't feel worth the DRY violation to do so. class String def word_wrap( col_width=80 ) self.dup.word_wrap!( col_width ) end def word_wrap!( col_width=80 ) self.gsub!( /(\S{#{col_width}})(?=\S)/, '\1 ' ) self.gsub!( /(.{1,#{col_width}})(?:\s+|$)/, "\\1\n" ) self end end The existing nano methods with these names do not properly deal with words or character sequences that are longer than the wrap width, so while these new methods are a little slower (3.03s vs. 2.35s) they are more correct. More testing should probably be done on speed optimizations and edge cases, though.