Show a string of certain length without truncating

后端 未结 4 911
天命终不由人
天命终不由人 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:00

    A very quick and dirty, iterative version:

    max_chars = 80
    text = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.'
    
    lines = []
    words = text.split
    
    while words.length > 0
      line = words.shift
    
      while words.first && (line.length + words.first.length + 1) <= max_chars
        line << " #{words.shift}" 
      end
    
      lines << line
    end
    
    lines.each { |line|  puts line }
    #=> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
    #   tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At
    #   vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,
    #   no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit
    #   amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut
    #   labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam
    #   et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
    #   sanctus est Lorem ipsum dolor sit amet.
    

提交回复
热议问题