I am displaying a string of certain length in ruby. only 80 characters of that string can be displayed in one line. for example if string length is 82 then it will be shown
Other option, not so clean, but...
The idea is to find the index of the spaces and substitute with \n the spaces at index close to the line length.
So, given the string str and the max_len:
delta = 0
(str + " ")
.each_char.with_index.with_object([]) { |(c, i), o| o << i if c == " "} # find the index of the spaces
.each_cons(2).with_object([]) do |(a, b), tmp| # select the index to be substituted
if b > (tmp.size + 1) * max_len + delta
tmp << a
delta = tmp.last - max_len * tmp.size + 1
end
end.each { |i| str[i] = "\n" } # substitute
Now str has \n when line length is close to max_len.
This alterates the original string.