Skip to content

Instantly share code, notes, and snippets.

@cayblood
Forked from jimweirich/presentation.rb
Created February 7, 2012 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cayblood/1759788 to your computer and use it in GitHub Desktop.
Save cayblood/1759788 to your computer and use it in GitHub Desktop.
Vital Ruby Lab 4
class Array
def sum
inject(0.0) { |result, el| result + el }
end
def mean
sum / size
end
end
class InvalidScoreError < RuntimeError
end
class Presentation
attr_reader :presentation_id, :title, :presenter, :subject, :scores
def initialize(presentation_id, title, presenter, subject)
@presentation_id, @title, @presenter, @subject = [presentation_id, title, presenter, subject]
@scores = []
end
def self.parse(line)
self.new(*line.split(':'))
end
def add_score(score)
raise InvalidScoreError if !score.is_a?(Integer) || score < 1 || score > 5
@scores << score
end
def average_score
return @scores.mean unless @scores.empty?
0.0
end
end
require 'presentation'
class Processor
def initialize
@presentations = []
end
def parse_presentations(text)
text.lines.each do |line|
@presentations << Presentation.parse(line)
end
end
def parse_votes(text)
text.lines.each do |line|
presentation_id, score = line.split
presentation = @presentations.detect {|presentation| presentation.presentation_id == presentation_id}
presentation.add_score(score.to_i)
end
end
def sorted_presentations
@presentations.sort_by {|presentation| presentation.average_score }
end
def good
sorted_presentations.select {|presentation| presentation.average_score >= 4.0 }
end
def bad
sorted_presentations.select {|presentation| presentation.average_score <= 2.0 }
end
def parse
parse_presentations(File.read('presentations.txt'))
parse_votes(File.read('votes.txt'))
puts "Good presentations:"
good.each do |presentation|
puts "#{sprintf("%.1f", presentation.average_score)} - #{presentation.title}"
end
puts
puts "Bad presentations:"
bad.each do |presentation|
puts "#{sprintf("%.1f", presentation.average_score)} - #{presentation.title}"
end
end
end
require 'processor.rb'
task :parse do
p = Processor.new
p.parse
end
task :default => :parse
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment