Class: WordWrapper
- Inherits:
-
Object
- Object
- WordWrapper
- Defined in:
- lib/word_wrapper.rb,
lib/greedy.rb,
lib/minimum_raggedness.rb
Overview
Implementation of word wrappign in Ruby. See README for usage.
Direct Known Subclasses
Defined Under Namespace
Classes: Greedy, MinimumRaggedness
Constant Summary collapse
- OneSpaceWidth =
1
- Infinity =
1/0.0
- Width =
100
Instance Attribute Summary collapse
-
#cost ⇒ Object
Returns the value of attribute cost.
-
#output ⇒ Object
Returns the value of attribute output.
-
#width ⇒ Object
Returns the value of attribute width.
-
#words ⇒ Object
Returns the value of attribute words.
Instance Method Summary collapse
-
#illegal_words ⇒ Array<String>
Any words in the text longer than the width of the output.
-
#initialize(width = Width, text = nil) ⇒ WordWrapper
constructor
A new instance of WordWrapper.
-
#line_cost(line) ⇒ Object
Calculate the cost of a line.
-
#total_cost(text) ⇒ Object
The total cost of a block of text.
Constructor Details
#initialize(width = Width, text = nil) ⇒ WordWrapper
Returns a new instance of WordWrapper.
8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/word_wrapper.rb', line 8 def initialize(width = Width, text = nil) @width = width if text @input = text elsif ARGV[0] begin @input = File.read(ARGV[0]) rescue Errno::ENOENT => e @input = ARGV[0] end else raise "You need to supply an input string or file" end end |
Instance Attribute Details
#cost ⇒ Object
Returns the value of attribute cost.
7 8 9 |
# File 'lib/word_wrapper.rb', line 7 def cost @cost end |
#output ⇒ Object
Returns the value of attribute output.
7 8 9 |
# File 'lib/word_wrapper.rb', line 7 def output @output end |
#width ⇒ Object
Returns the value of attribute width.
7 8 9 |
# File 'lib/word_wrapper.rb', line 7 def width @width end |
#words ⇒ Object
Returns the value of attribute words.
7 8 9 |
# File 'lib/word_wrapper.rb', line 7 def words @words end |
Instance Method Details
#illegal_words ⇒ Array<String>
Any words in the text longer than the width of the output
38 39 40 |
# File 'lib/word_wrapper.rb', line 38 def illegal_words @words.select{ |word| word.length > @width } end |
#line_cost(line) ⇒ Object
Calculate the cost of a line. Cost is defined as
[ Trailing whitespace ] ^ 2
26 27 28 |
# File 'lib/word_wrapper.rb', line 26 def line_cost(line) (@width - line.strip.length)**2 # no lines will ever start with whitespace end |
#total_cost(text) ⇒ Object
The total cost of a block of text
32 33 34 |
# File 'lib/word_wrapper.rb', line 32 def total_cost(text) text.split("\n").inject(0){ |acc, line| acc + line_cost(line) } end |