Class: WordWrapper

Inherits:
Object
  • Object
show all
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

Greedy, MinimumRaggedness

Defined Under Namespace

Classes: Greedy, MinimumRaggedness

Constant Summary collapse

OneSpaceWidth =
1
Infinity =
1/0.0
Width =
100

Instance Attribute Summary collapse

Instance Method Summary collapse

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

#costObject

Returns the value of attribute cost.



7
8
9
# File 'lib/word_wrapper.rb', line 7

def cost
  @cost
end

#outputObject

Returns the value of attribute output.



7
8
9
# File 'lib/word_wrapper.rb', line 7

def output
  @output
end

#widthObject

Returns the value of attribute width.



7
8
9
# File 'lib/word_wrapper.rb', line 7

def width
  @width
end

#wordsObject

Returns the value of attribute words.



7
8
9
# File 'lib/word_wrapper.rb', line 7

def words
  @words
end

Instance Method Details

#illegal_wordsArray<String>

Any words in the text longer than the width of the output

Returns:

  • (Array<String>)

    illegal words



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

Parameters:

  • line (String)

    to compute cost for



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

Parameters:

  • text (String)


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