Ad
Strings
Data Types
Regular Expressions
Declarative Programming
Advanced Language Features
Programming Paradigms
Fundamentals
Code
Diff
  • class String
      def justify(width)
        return self if self.length <= width
        
        newline = "\n"
        paragraph_separator = newline * 2
        space = ' '
        
        paragraphs = split paragraph_separator
        
        if paragraphs.length > 1
          paragraphs.map {|paragraph| paragraph.justify width }.join paragraph_separator
        elsif include? newline
          gsub(newline, space).justify width
        else
          space_index = slice(0, width.succ).rindex(space) || index(space, width)
          [slice(0, space_index), slice(space_index..-1).lstrip.justify(width)].join newline
        end
      end
    end
    
    • 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
    • class String
    • def justify(width)
    • return self if self.length <= width
    • newline = "\n"
    • paragraph_separator = newline * 2
    • space = ' '
    • paragraphs = split paragraph_separator
    • if paragraphs.length > 1
    • paragraphs.map {|paragraph| paragraph.justify width }.join paragraph_separator
    • elsif include? newline
    • gsub(newline, space).justify width
    • else
    • space_index = slice(0, width.succ).rindex(space) || index(space, width)
    • [slice(0, space_index), slice(space_index..-1).lstrip.justify(width)].join newline
    • end
    • end
    • end