method

word_wrap

word_wrap(text, *args)
public

Wraps the text into lines no longer than line_width width. This method breaks on the first whitespace character that does not exceed line_width (which is 80 by default).

Examples

word_wrap('Once upon a time')
# => Once upon a time

word_wrap('Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding a successor to the throne turned out to be more trouble than anyone could have imagined...')
# => Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding\n a successor to the throne turned out to be more trouble than anyone could have\n imagined...

word_wrap('Once upon a time', :line_width => 8)
# => Once upon\na time

word_wrap('Once upon a time', :line_width => 1)
# => Once\nupon\na\ntime

You can still use word_wrap with the old API that accepts the line_width as its optional second parameter:

word_wrap('Once upon a time', 8)     # => Once upon\na time

2Notes

Wrapping peculiarities as of 2.x

metavida · Oct 14, 2008

In Rails 2.x word_wrap has been improved so that it no longer consumes multiple line-breaks or leading & trailing line-breaks.

word_wrap("\

Once upon a time

The End
") # =>
Once upon a time

The End

However it still doesn't break long words

"supercalifragilisticexpialidocious".length
# => 30
word_wrap("\

Once upon a supercalifragilisticexpialidocious time", 15) # =>
Once upon a
supercalifragilisticexpialidocious
time

word_wrap with breaking long words

mihserf · Nov 18, 2010

====Code def breaking_word_wrap(text, *args) options = args.extract_options! unless args.blank? options[:line_width] = args[0] || 80 end options.reverse_merge!(:line_width => 80) text = text.split(" ").collect do |word| word.length > options[:line_width] ? word.gsub(/(.{1,#{options[:line_width]}})/, "\\1 ") : word end * " " text.split("
").collect do |line| line.length > options[:line_width] ? line.gsub(/(.{1,#{options[:line_width]}})(\s+|$)/, "\\1
").strip : line end * "
" end

breaking_word_wrap("Once upon a supercalifragilisticexpialidocious time",15)

=> Once upon a\

supercalifragil
isticexpialidoc
ious time