Skip to content

Instantly share code, notes, and snippets.

@cayblood
Forked from jimweirich/presentation.rb
Created February 7, 2012 08:12
Show Gist options
  • Save cayblood/1758188 to your computer and use it in GitHub Desktop.
Save cayblood/1758188 to your computer and use it in GitHub Desktop.
Vital Ruby Lab 3
class Array
def sum
inject(0.0) { |result, el| result + el }
end
def mean
sum / size
end
end
class InvalidScoreError < Exception
end
class Presentation
attr_accessor :title, :presenter
def initialize(title, presenter)
@title, @presenter = [title, presenter]
@scores = []
end
def add_score(score)
raise InvalidScoreError if !score.is_a?(Integer) || score < 1 || score > 5
@scores << score
end
def average_score
@scores.mean
end
end
require 'spec_helper'
require 'presentation'
describe Presentation do
let(:presentation) { Presentation.new("TITLE", "PRESENTER") }
it "has a title and presenter" do
presentation.title.should == "TITLE"
presentation.presenter.should == "PRESENTER"
end
it "can have scores added to it" do
lambda { presentation.add_score(4) }.should_not raise_error
end
it "can calculate the average score with a single score" do
presentation.add_score(4)
presentation.average_score.should == 4
end
it "can calculate the average of two scores" do
presentation.add_score(4)
presentation.add_score(5)
presentation.average_score.should be_within(0.001).of(4.5)
end
it "rejects too large scores with an error" do
lambda {
presentation.add_score(6)
}.should raise_error(InvalidScoreError)
end
it "rejects too small scores with an error" do
lambda {
presentation.add_score(0)
}.should raise_error(InvalidScoreError)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment