Skip to content

Instantly share code, notes, and snippets.

@ScottGo
Last active December 15, 2015 22:29
Show Gist options
  • Save ScottGo/5333625 to your computer and use it in GitHub Desktop.
Save ScottGo/5333625 to your computer and use it in GitHub Desktop.
Calculating the mean of an array of numbers
describe 'mean' do
let(:array_1) { [1, 2, 3, 4, 5, 5, 7] }
let(:array_2) { [4, 4, 5, 5, 6, 6, 6, 7] }
it "is defined as a method" do
defined?(mean).should eq 'method'
end
it "requires a single argument" do
method(:mean).arity.should eq 1
end
it "returns the correct mean of array 1" do
mean(array_1).should eq 3.857142857142857
end
it "returns the correct mean of array 2" do
mean(array_2).should eq 5.375
end
end
def mean(array)
arraycnt = array.count
sum = 0
array.each do |i|
sum += i
end
sumtotal = sum / arraycnt
return sumtotal.to_f
end
#let(:array_1) { [1, 2, 3, 4, 5, 5, 7] } sum = 27
#let(:array_2) { [4, 4, 5, 5, 6, 6, 6, 7] } sum = 43
#The mean is the average of the numbers.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment