Skip to content

Instantly share code, notes, and snippets.

@gicappa
Created February 24, 2014 12:16
Show Gist options
  • Save gicappa/9187330 to your computer and use it in GitHub Desktop.
Save gicappa/9187330 to your computer and use it in GitHub Desktop.
require "test/unit"
class VarianceTest < Test::Unit::TestCase
def test_it_should_compute_the_average_out_of_an_array
assert_equal(50, [40, 30, 50, 80].average)
end
def test_it_should_compute_variance_out_of_an_array
assert_equal(350, [40, 30, 50, 80].variance)
end
end
class Array
def self.average(array)
array.reduce(:+).to_f / array.size
end
def average
self.class.average self
end
def variance
self.class.average map { |n| (n - average) ** 2 }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment