Class: Meekster::BallotFile

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ BallotFile

Returns a new instance of BallotFile.



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/meekster/ballot_file.rb', line 7

def initialize(options={})
  if options[:filename]
    @file = File.open(options[:filename], 'r')
  elsif options[:string]
    @file = StringIO.new(options[:string])
  elsif options[:file]
    @file = options[:file]
  end

  @read = false
end

Instance Attribute Details

#ballotsObject

Returns the value of attribute ballots.



5
6
7
# File 'lib/meekster/ballot_file.rb', line 5

def ballots
  @ballots
end

#candidatesObject

Returns the value of attribute candidates.



5
6
7
# File 'lib/meekster/ballot_file.rb', line 5

def candidates
  @candidates
end

#seatsObject

Returns the value of attribute seats.



5
6
7
# File 'lib/meekster/ballot_file.rb', line 5

def seats
  @seats
end

Instance Method Details

#read!Object



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
# File 'lib/meekster/ballot_file.rb', line 19

def read!
  @file.rewind

  @ballots = []

  candidates_and_seats = @file.gets
  @candidate_count, @seats = candidates_and_seats.split(' ').map{|n| n.to_i}

  @candidates = Array.new(@candidate_count){Meekster::Candidate.new}

  ballot_line = @file.gets

  until ballot_line.match(/^0/)
    line_atoms = ballot_line.split(' ')

    count = line_atoms.delete_at(0).to_i
    line_atoms.delete_at(-1)

    ranking = line_atoms.map{|id| @candidates[id.to_i - 1]}

    count.times do
      @ballots << Meekster::Ballot.new(ranking)
    end

    ballot_line = @file.gets

  end

  @candidate_count.times do |i|
    candidate_name = @file.gets.strip
    # Remove double-quotes
    candidate_name = candidate_name.match(/\A\"(.*)\"\Z/)[1]
    @candidates[i].name = candidate_name
  end

  @read = true
end

#read?Boolean

Returns:

  • (Boolean)


57
58
59
# File 'lib/meekster/ballot_file.rb', line 57

def read?
  !!@read
end