Skip to content

Instantly share code, notes, and snippets.

@Boztown
Created August 21, 2015 03:06
Show Gist options
  • Save Boztown/b1649fc0a1225ee175d6 to your computer and use it in GitHub Desktop.
Save Boztown/b1649fc0a1225ee175d6 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'csv'
class GrantGainsCalculator
@employees
@market_price_date
@market_price
def initialize(data)
@data = data
#@investments = Array.new
@employees = Array.new
CSV.parse(data) do |row|
new_employee = false
# first line is row count; disregard for now
next if row.count == 1
if row.count == 2
self.market_price_date = row[0]
self.market_price = row[1]
next
end
unless @employees.any?{|a| a.id == row[1]}
employee = Employee.new(row[1])
new_employee = true
else
employee = @employees.find {|s| s.id == row[1] }
end
investment = Investment.new
investment.investment_type = row[0]
investment.investment_date = row[2]
investment.units = row[3]
investment.grant_price = row[4]
employee.investments << investment
@employees << employee if new_employee
end
end
def calculate
output = Array.new
@employees.each do |employee|
row = Array.new
last_employee_id = nil
total_value = 0
employee.investments.each do |investment|
\
last_employee_id = employee.id
grant_value = investment.units * investment.grant_price
market_value = investment.units * @market_price
diff_value = market_value - grant_value
total_value += diff_value
end
row[0] = last_employee_id
row[1] = total_value
output << row
end
output.sort! do |a, b|
a[0] <=> b[0]
end
csv_string = CSV.generate do |csv|
output.each do |o|
csv << o
end
end
puts csv_string
end
def market_price= market_price
@market_price = market_price.to_f
end
def market_price_date= market_price_date
@market_price_date = Date.parse market_price_date
end
end
class Employee
attr_accessor :id, :investments
@id
@investments
def initialize(id)
@id = id
@investments = Array.new
end
end
class Investment
attr_accessor :investment_type,
:customer_id, :investment_date,
:units, :grant_price
@investment_type
@customer_id
@investment_date
@units
@grant_price
def investment_date= investment_date
@investment_date = Date.parse investment_date
end
def units= units
@units = units.to_i
end
def grant_price= grant_price
@grant_price = grant_price.to_f
end
end
input = ARGF.read
calculator = GrantGainsCalculator.new(input)
calculator.calculate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment