Skip to content

Instantly share code, notes, and snippets.

@rondale-sc
Created November 8, 2011 02:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rondale-sc/1346872 to your computer and use it in GitHub Desktop.
Save rondale-sc/1346872 to your computer and use it in GitHub Desktop.
Down and Dirty Stats
require 'bigdecimal'
require 'csv'
require 'pp'
class Stats
include Enumerable
def initialize(array)
standardize_array(array)
end
def to_csv(file_path)
file_path ||= "./stats.csv"
CSV.open(file_path, "w") do |csv|
csv << ["Results"]
@array.each do |result|
csv << [result.to_s("F")]
end
end
end
def standardize_array(array)
@array = []
array.map do |element|
if element.class == BigDecimal then next
elsif element.class == Fixnum then @array << BigDecimal.new(element.to_s)
elsif element.class == Float then @array << BigDecimal.new(element.to_s)
elsif element.class == String && element =~ /\A\d+(\.|)\d+\z/ then @array << BigDecimal.new(element)
else raise StandardError, "Incompatible elements provided."
end
end
end
def <<(element)
@array << element
standardize_array(@array)
end
def sum
@array.inject(BigDecimal.new("0")) {|memo,item| memo + item }
end
def mean
sum / @array.length
end
def sample_variance
@array.inject(BigDecimal.new("0")) { |memo,element| memo += (element - mean) ** 2 } / BigDecimal.new((@array.length - 1).to_s)
end
def standard_deviation
Math.sqrt(sample_variance)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment