From: Lou Vanek Date: 2006-03-13T22:16:23+09:00 Subject: Re: word_wrap method for String? here's a (partially modded) excerpt from a previous discussion on this topic: width = 11 str = 'This is a test of the emergency broadcasting servicings I asseverate' p str.scan(/\S.{0,#{width}}\S(?=\s|$)|\S+/) Jeff Coleman wrote: > Hi all, > > For a text adventure program I'm working on I needed a method to word > wrap a long string based on spaces or non-word characters so I came up > with this. I just thought I'd post it to see if there are any thoughts > or if there might be a better way to do it. > > class String > def word_wrap(width) > source = self.dup > original_width = width > while width < source.length do > last_space = source.rindex( / |\W/, width ) > source.insert( last_space, "\n" ) > source.gsub!(/\n */,"\n") > width = last_space + original_width > end > source > end > end > > Jeff Coleman >