Skip to content

Instantly share code, notes, and snippets.

@kimenye
Created October 3, 2012 11:13
Show Gist options
  • Save kimenye/3826433 to your computer and use it in GitHub Desktop.
Save kimenye/3826433 to your computer and use it in GitHub Desktop.
Supermarket
class Fruit
attr_accessor :type, :unit_price, :discount_quantity, :discount_price, :offer
def initialize(type,unit_price, discount_quantity=nil, discount_price=nil, offer=false)
@type = type
@unit_price = unit_price
@discount_quantity = discount_quantity
@discount_price = discount_price
@offer = offer
end
def calculate_price(quantity)
@unit_price * quantity
end
end
class Mango < Fruit
def initialize()
super(type="Mango", unit_price=20, discount_quantity = 2, discount_price=15, offer=true)
end
def calculate_price(quantity)
total_price = 0
if quantity >= @discount_quantity
total_price = @discount_price * quantity
else
total_price = @unit_price * quantity
end
total_price
end
end
class Banana < Fruit
def initialize()
super(type="Banana", unit_price=30)
end
end
class Checkout
attr_accessor :products
def initialize(customer)
@products = []
@customer = customer
end
def price
total_price = 0
# @products.each { |p| total_price += p.unit_price }
types = product_types
types.each do |t|
num = qty_by_type(t)
ut = unique_type(t)
total_price += ut.calculate_price(num)
end
total_price
end
def product_types
types = @products.collect{ |p| p.type }.uniq
end
def unique_type (type)
@products.detect{ |p| p.type == type }
end
def qty_by_type(type)
matching = @products.select{ |p| p.type == type }
matching.length
end
def scan(product)
@products << product
end
end
m = Mango.new
m2 = Mango.new
b = Banana.new
# puts m.type
# m.price = 100
c = Checkout.new("P")
c.scan(m)
c.scan(b)
c.scan(m2)
# ut = c.unique_types.length
num_mangoes = c.qty_by_type("Mango")
product_types = c.product_types
# puts "U #{ut} "
puts "We have #{product_types.length} product types"
puts "We have #{num_mangoes} mangoes"
puts "total price #{c.price}"
# binding.pry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment