method

word_wrap

word_wrap(text, line_width = 80)
public

Word wrap long lines to line_width.

3Notes

Wrapping peculiarities

metavida · Oct 14, 20081 thank

word_wrap will consume multiple line-breaks as well as leading & trailing line-breaks.

word_wrap("\

Once upon a time

The End
") # => Once upon a time
The End

word_wrap will NOT break long words

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

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

If you want a function that will break long words & maintain multiple line-breaks try this alternative. Note it does add a line break at the end of the output.

def breaking_wrap_wrap(txt, col = 80)
txt.gsub(/(.{1,#{col}})( +|$\

?)|(.{1,#{col}})/, "\\1\\3
") end

breaking_wrap_wrap("\

Once upon a supercalifragilisticexpialidocious time", 15) # =>
Once upon a
supercalifragil
isticexpialidoc
ious time\

Regex-based code from http://blog.macromates.com/2006/wrapping-text-with-regular-expressions/

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