From: Matthew Harris Date: 2006-03-13T22:34:07+09:00 Subject: Re: word_wrap method for String? Mike wrote: >> 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. >> > > I wrote one last week, actually > > def wrap(wrap_len=78) > start_pos = wrap_len > while start_pos < @fact.length > sp = @fact.rindex(' ', start_pos) > @fact.insert(sp, '|') > start_pos = sp + wrap_len + 1 > end > @fact.gsub!(/\|[\s]/, "\n") > end > > I'm far from an expert, so I don't know which method may be better :) > > -M class String # Wrap string by the given length, and join it with the given character. # The method doesn't distinguish between words, it will only work based on # the length. The method will also strip and whitespace. # def wrap(length = 80, character = $/) scan(/.{#{length}}|.+/).map { |x| x.strip }.join(character) end end puts 'Hello, World! I am quite very long :)'.wrap(15, "
\n") # Output: # # Hello, World! I
# am quite very
# long :) Have fun =) - Matt -- Posted via http://www.ruby-forum.com/.