Skip to content

Instantly share code, notes, and snippets.

@Jared-Prime
Created April 26, 2012 05:05
Show Gist options
  • Save Jared-Prime/2496104 to your computer and use it in GitHub Desktop.
Save Jared-Prime/2496104 to your computer and use it in GitHub Desktop.
require 'rspec'
require './../core_arithmetic'
class DataSet < Array
def input(data)
if data.kind_of?(Enumerable)
data.each do |item|
if item.kind_of?(Numeric) == true
self << item
else
self.input(item)
end
end
elsif data.kind_of?(Numeric)
self << data
else
begin
raise RuntimeError
rescue
puts "is the data numerable?"
end
end
end
end
## need to extend the Array class in order to perform basic math. Otherwise,
# the methods tend to crash as they attempt to run on Array instances.
class Array
def sum
self.inject(0) do |a,x|
a + x
end
end
def average
self.sum.to_f / self.size
end
def median
case self.size % 2
when 0 then self.sort[self.size/2-1,2].average
when 1 then self.sort[self.size/2].to_f
end if self.size > 0
end
end
#########################
describe DataSet do
it "inherits from Array" do
DataSet.kind_of?(Array) == true
end
it "returns 0 for an empty array" do
DataSet.new.sum.should eq 0
end
it "finds the total value of its data" do
data = DataSet.new
data << 1
data << 2
data.sum.should eq 3
end
it "inputs data one at a time or in batches" do
example1 = DataSet.new.input(1)
example1.first.should eq 1
example2 = DataSet.new.input([1,2,3])
example2.last.should eq 3
example3 = DataSet.new.input((4..6))
example3.last.should eq 6
example4 = DataSet.new.input(1.3)
example4.last.should be_a_kind_of Float
end
it "takes numerical data only" do
data = "cat"
DataSet.new.input("cat").should raise_error
end
it "knows its average value" do
example = DataSet.new
example.input(1..100)
example.average.should eq 50.5
end
it "knows its median (aka middle) value" do
example = DataSet.new
example.input(1..100)
example.median.should eq 50.5
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment