Home > database >  how to break long text to smaller lines by words in ruby/rails?
how to break long text to smaller lines by words in ruby/rails?

Time:03-09

How to break long text to smaller lines by words? Ideally, I need method like

def text_splitter(text, line_size = 5)
    # ...
end

text_splitter("a b c d e text longword") # => ["a b c", "d e ", "text ", "longword"]

CodePudding user response:

Rails comes with the word_wrap helper which can split long lines based on a given line width. It always splits at whitespace so long words won't get split / cut.

In rails/console:

lines = helper.word_wrap("a b c d e text longword", line_width: 5)
#=> "a b c\nd e\ntext\nlongword"

puts lines

Output:

a b c
d e
text
longword

Note that it returns a string, not an array.

  • Related