Class: WordWrap::Wrapper
- Inherits:
-
Object
- Object
- WordWrap::Wrapper
- Defined in:
- lib/word_wrap/wrapper.rb
Instance Method Summary collapse
- #fit ⇒ Object
-
#initialize(text, width) ⇒ Wrapper
constructor
A new instance of Wrapper.
- #split_line(line, width) ⇒ Object
- #wrap ⇒ Object
Constructor Details
#initialize(text, width) ⇒ Wrapper
Returns a new instance of Wrapper.
9 10 11 12 |
# File 'lib/word_wrap/wrapper.rb', line 9 def initialize(text, width) @text = text @width = width end |
Instance Method Details
#fit ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/word_wrap/wrapper.rb', line 14 def fit lines = [] next_line = "" continued = false @text.lines do |line| line.chomp! "\n" if line.length == 0 if next_line.length > 0 lines.push next_line next_line = "" end lines.push "" end words = line.split " " words.each do |word| word.chomp! "\n" if next_line.length + word.length < @width if next_line.length > 0 next_line << " " << word else next_line = word end else if word.length >= @width lines.push next_line unless next_line == "" lines.push word next_line = "" else lines.push next_line next_line = word end end end end lines.push next_line if next_line.length <= 0 lines.join("\n") else lines.join("\n") + "\n" end end |
#split_line(line, width) ⇒ Object
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# File 'lib/word_wrap/wrapper.rb', line 80 def split_line(line, width) at = line.index /\s/ last_at = at while at != nil && at < width last_at = at at = line.index /\s/, last_at + 1 end if last_at == nil [line] else [line[0,last_at], line[last_at+1, line.length]] end end |
#wrap ⇒ Object
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/word_wrap/wrapper.rb', line 60 def wrap output = [] @text.lines do |line| line.chomp! "\n" if line.length > @width new_lines = split_line(line, @width) while new_lines.length > 1 && new_lines[1].length > @width output.push new_lines[0] new_lines = split_line new_lines[1], @width end output += new_lines else output.push line end end output.map { |s| s.rstrip! } output.join("\n") + "\n" end |