0

Possible Duplicate:
Wrapping text into lines at word boundaries

I need to take a textarea input from a user and break it up into multiple lines every thirty chars. The hard part is I also need to make sure the line break occurs at a " "(space) in order to not break up words.

My initial attempt in trying to figure this out looked like this:

if @square.text.length > 30
  text = @square.text[0, 31] + "\n" + @square.text[31, @square.text.length]
else
   text = @square.text
end

Also, I know the above only handles a string that needs to be broken up once. I need up-to six line breaks.

Any ideas how to go about this?

Community
  • 1
  • 1
Deekor
  • 9,144
  • 16
  • 69
  • 121
  • 1
    You cannot always break by words at exactly every thirty characters. I think you mean breaking with maximum thirty characters. Also, what do you want to happen if there is a word exceeding thirty characters and there is no way to break? Another point unclear is, when you break at a space, do you want to start the next line with that space or remove it (replace with new line)? Still another point is: what is `@square`? Don't use variables without explanation. Or, simplify it to fit the format of a question. – sawa Oct 08 '12 at 22:40
  • Take a glance at http://stackoverflow.com/questions/754407/what-is-the-best-way-to-chop-a-string-into-chunks-of-a-given-length-in-ruby – rjz Oct 08 '12 at 22:40

1 Answers1

2

Use word_wrap from the text helper:

include ActionView::Helpers::TextHelper
# or, if you are in a controller
# helper :text

word_wrap(@square.text, :line_width => 30)
rewritten
  • 16,280
  • 2
  • 47
  • 50