word_wrap(text, line_width = 80) public

Word wrap long lines to line_width.

Show source
Register or log in to add new notes.
October 14, 2008 - (>= v2.0.0)
0 thanks

Wrapping peculiarities as of 2.x

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("\nOnce upon a time\n\nThe End\n")
  # => \nOnce upon a time\n\nThe End

However it still doesn’t break long words

  "supercalifragilisticexpialidocious".length
  # => 30
  word_wrap("\nOnce upon a supercalifragilisticexpialidocious time", 15)
  # => \nOnce upon a\nsupercalifragilisticexpialidocious\ntime
October 14, 2008 - (v1.0.0 - v1.2.6)
0 thanks

Wrapping peculiarities

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

  word_wrap("\nOnce upon a time\n\nThe End\n")
  # => Once upon a time\nThe End

word_wrap will NOT break long words

  "supercalifragilisticexpialidocious".length
  # => 34
  word_wrap("\nOnce upon a supercalifragilisticexpialidocious time", 15)
  # => Once upon a\nsupercalifragilisticexpialidocious\ntime

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}})( +|$\n?)|(.{1,#{col}})/,
      "\\1\\3\n")
  end

  breaking_wrap_wrap("\nOnce upon a supercalifragilisticexpialidocious time", 15)
  # => \nOnce upon a\nsupercalifragil\nisticexpialidoc\nious time\n

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