Class: String

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

Instance Method Summary collapse

Instance Method Details

#wrap(limit = 50, opts = {}) ⇒ Object



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

def wrap(limit = 50, opts={})
  strip!
  indent = opts[:indent] || ''
  return indent << self if size + indent.size <= limit || !include?(' ')
  
  words = self.split(/\s/)
  lines = [[indent]]
  char_count = indent.size
  words.each do |word|
    word_size = word.size + 1
    if (word_size + char_count <= limit) || lines.last.size == 1
      char_count += word_size
      lines.last << word
    else
      char_count = word_size + indent.size
      lines << [indent, word]
    end
  end
  lines.map do |line| 
    indent = line.shift
    indent + line.join(' ')
  end.join("\n")
end