Skip to content

Instantly share code, notes, and snippets.

@andyh

andyh/taxes.rb Secret

Created April 3, 2013 12:33
Show Gist options
  • Save andyh/49405ac9ffe06b4a2731 to your computer and use it in GitHub Desktop.
Save andyh/49405ac9ffe06b4a2731 to your computer and use it in GitHub Desktop.
require "bigdecimal"
class Receipt
def initialize
@items = []
@total_tax = BigDecimal.new(0.0,2)
@total_cost = BigDecimal.new(0.0,2)
end
def add(item)
@items.push(item)
end
def total_cost
@items.each do |item|
@total_cost+= item.price
end
@total_cost.round(2).to_s("F")
end
def total_tax
@items.each do |item|
@total_tax+= item.tax_calc
end
@total_tax.round(2).to_s("F")
end
end
class Item
attr_reader :name, :quantity, :cost
def initialize(name, quantity, cost)
@name = name
@quantity = quantity
@cost = BigDecimal.new(cost,2)
end
def price
quantity * cost
end
def tax_calc
price * tax_rate
end
def tax_rate
case name
when /Imported Bottle of Perfume/i, /Imported Box of Chocolate/i
BigDecimal.new(0.15, 2)
when /Bottle of Perfume/i, /Music CD/i
BigDecimal.new(0.10,2)
when /Book/i, /Chocolate Bar/i, /Packet of Headache Pills/i
BigDecimal.new(0.00,2)
end
end
end
receipt = Receipt.new
receipt.add Item.new("Book", 10, 5.50)
receipt.add Item.new("Bottle of Perfume", 1, 95.00)
puts "Sales Taxes: " + receipt.total_tax
puts "Total: " + receipt.total_cost
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment