Class: Candidates

Inherits:
Object
  • Object
show all
Defined in:
lib/my_segments/candidates.rb

Direct Known Subclasses

Candidate

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCandidates

Returns a new instance of Candidates.



5
6
7
8
# File 'lib/my_segments/candidates.rb', line 5

def initialize
	@candidates = Array.new # An array of candidate objects
	self
end

Instance Attribute Details

#candidatesObject

Returns the value of attribute candidates.



3
4
5
# File 'lib/my_segments/candidates.rb', line 3

def candidates
  @candidates
end

Instance Method Details

#add(candidate) ⇒ Object



14
15
16
17
# File 'lib/my_segments/candidates.rb', line 14

def add(candidate)
	@candidates << candidate
	self
end

#has_id?(id) ⇒ Boolean

Returns whether or not the array contains a candidate with this solution id

Returns:

  • (Boolean)


26
27
28
# File 'lib/my_segments/candidates.rb', line 26

def has_id?(id)
	@candidates.collect(&:id).include?(id)
end

#pruneObject



10
11
12
# File 'lib/my_segments/candidates.rb', line 10

def prune
 @candidates.delete_if { |x| x.votes < 1 }
end

#remove(index) ⇒ Object

Removes the candidate at the specified index



20
21
22
# File 'lib/my_segments/candidates.rb', line 20

def remove(index)
	@candidates.delete_at(index)
end

#sizeObject

Returns the number of candidates



50
51
52
# File 'lib/my_segments/candidates.rb', line 50

def size
	@candidates.size
end

#sort_by_rankObject

Returns an array of candidates, sorted by their rank



39
40
41
42
# File 'lib/my_segments/candidates.rb', line 39

def sort_by_rank
	sorted = @candidates.sort{ |x,y| y.votes <=> x.votes }
	@candidates
end

#to_sObject

Pretty prints the array of candidates



55
56
57
58
59
60
61
62
63
# File 'lib/my_segments/candidates.rb', line 55

def to_s
	s = ''
	unless @candidates == nil
		@candidates.each do |c|
			s += "[#{c.id}, #{c.misspelled}, #{c.solution}, #{c.votes}]\n"
		end
	end
   return s
end

#total_votesObject

Returns the total number of votes



45
46
47
# File 'lib/my_segments/candidates.rb', line 45

def total_votes
	@candidates.inject(0) { |sum, c| sum + c.votes }
end

#vote_for(id, value) ⇒ Object

Increments the votes of the given candidate by the value. Returns the affected candidate object



32
33
34
35
36
# File 'lib/my_segments/candidates.rb', line 32

def vote_for(id, value)
	candidate = @candidates[@candidates.collect(&:id).index(id)]
	candidate.votes += value
	candidate
end