method

word_wrap

word_wrap(text, line_width: 80, break_sequence: "\\n")
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).

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\na successor to the throne turned out to be more trouble than anyone could have\nimagined..."

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

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

You can also specify a custom break_sequence (“n” by default):

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

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