Skip to content

Instantly share code, notes, and snippets.

@neerajsingh0101
Forked from sharmaabhinav/Price_calculator.rb
Created August 31, 2014 19:56
Show Gist options
  • Save neerajsingh0101/704146d76b0c65874a83 to your computer and use it in GitHub Desktop.
Save neerajsingh0101/704146d76b0c65874a83 to your computer and use it in GitHub Desktop.
class PriceCalculator
ITEM_UNIT_PRICES = {
milk: 3.97,
bread: 2.17,
banana: 0.99,
apple: 0.89
}
SALE_PRICES = {
milk: {
quantity: 2,
price: 5.00
},
bread: {
quantity: 3,
price: 7.00
}
}
def user_input
puts "Please enter all the items purchased separated by a comma"
@items = gets.chomp.split(',')
convert_user_input_to_item_quantities
end
def calculate_price
total_price = 0
@item_quantities.each do |item, quantity|
if !SALE_PRICES[item].nil?
quantity_on_sale_price = quantity / SALE_PRICES[item][:quantity]
quantity_on_unit_price = quantity % SALE_PRICES[item][:quantity]
sale_price = SALE_PRICES[item][:price]
unit_price = ITEM_UNIT_PRICES[item]
total_price += quantity_on_sale_price * sale_price + quantity_on_unit_price * unit_price
else
total_price += quantity * ITEM_UNIT_PRICES[item]
end
end
total_price.round(2) # round off to 2 digits after decimal
end
private
def convert_user_input_to_item_quantities
@items.each do |item|
item.gsub!(" ","")
end
@item_quantities = {
milk: 0,
bread: 0,
banana: 0,
apple: 0
}
@items.each do |item|
case item
when 'apple'
@item_quantities[:apple] += 1
when 'milk'
@item_quantities[:milk] += 1
when 'bread'
@item_quantities[:bread] += 1
when 'banana'
@item_quantities[:banana] += 1
end
end
end
end
pc = PriceCalculator.new
pc.user_input
puts "Total cost: " + pc.calculate_price.to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment