Skip to content

Instantly share code, notes, and snippets.

@subbu
Created October 27, 2009 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save subbu/219759 to your computer and use it in GitHub Desktop.
Save subbu/219759 to your computer and use it in GitHub Desktop.
require 'yaml'
module Tax
SALES_TAX = 10
SALES_TAX_EXEMPTIONS = ['book', 'chocolate', 'pills' ]
IMPORT_DUTY = 5
end
# There is no standard method that rounds off a float to 2 decimals.
class Float
def round_to(x)
(self * 10**x).round.to_f / 10**x
end
end
class Item
def initialize(attributes)
return if attributes.length < 0
attributes.each do |name, value|
instance_variable_set "@#{name}", value
end
end
def exempted?
Tax::SALES_TAX_EXEMPTIONS.any?{|i| @item.downcase.include?(i.downcase)}
end
def imported?
!@item.scan(/imported/i).empty?
end
def sales_tax
base_tax = exempted? ? 0 : Tax::SALES_TAX
import_duty = imported? ? Tax::IMPORT_DUTY : 0
tax_rate = base_tax + import_duty
total_tax = (@price.to_f*tax_rate)/100
total_tax.round_to(2)
end
def price
(@price.to_f + sales_tax).round_to(2)
end
def print_receipt
puts "Item: #{@item}, Quantity: #{@quantity}, Price: #{price}"
end
alias_method :p, :print_receipt
end
inputs = YAML.load(File.open('inputs.yml'))
inputs.sort.each do |label, values|
puts "Processing #{label.gsub('_',' ').capitalize}:"
totals = values.collect do |item, value|
item, price = value.split(/\s+at\s+/)
quantity, item = item.split(/\s/, 2)
billed_item = Item.new(:item => item, :quantity => quantity, :price => price)
billed_item.p
[billed_item.price, billed_item.sales_tax]
end
t = totals.inject do |sum, v|
[sum[0] + v[0], sum[1] + v[1]]
end
puts "-----------------------"
puts "Total Sales Taxes: #{t[1]}"
puts "Total: #{t[0]}", ""
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment