Show a string of certain length without truncating

后端 未结 4 961
天命终不由人
天命终不由人 2021-01-20 22:18

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

4条回答
  •  遇见更好的自我
    2021-01-20 23:09

    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.

提交回复
热议问题