Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/justify.rb

Instance Method Summary collapse

Instance Method Details

#justify(len = 80) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/justify.rb', line 4

def justify(len = 80)
  unless self.length < len

    words = self.gsub("\n", " ").scan(/[\w.-]+/)
    actual_len = 0
    output = ""
    words.each do |w|
      output += w
      actual_len += w.length
      if actual_len >= len
        output += "\n"
        actual_len = 0
      else
        output += " "
      end
    end
    return output
  else
    self
  end

end