Ad
Strings
Data Types
Regular Expressions
Declarative Programming
Advanced Language Features
Programming Paradigms
Fundamentals

Write a function that format a long text breaking it up with newlines for a given width.

For example,

"Roses are red violets are blue".justify(20) should return
"Roses are red
violets are blue"

It should keep existing paragraphs (two and more newlines in a row), if there are.

"Poem 1

Roses are red
My name is Dave".justify(20) should return the same:
"Poem 1

Roses are red
violets are blue"

class String
  def justify(len)
    unless self.length < len
      words = self.scan(/[\w,.-]+(?:\n{2,})?/)
      actual_len = 0
      output = ""
      words.each do |w|
        if actual_len >= len
          output += "\n"
        else
          output += " " if output > "" and !output[-1].eql?"\n" and actual_len + w.length<=len
        end
        actual_len = 0 if output[-1].eql?"\n"
        if (actual_len == 0) or actual_len + w.length<=len
          output += w
          actual_len += w.length + 1
        else
          output += "\n" + w
          actual_len = w.length + 1
        end
      end
      return output.rstrip
    else
      self
    end
  end
end