Skip to content

Instantly share code, notes, and snippets.

@sharmaabhinav
Last active January 19, 2021 10:16
Show Gist options
  • Save sharmaabhinav/07774d64f8c02b316414 to your computer and use it in GitHub Desktop.
Save sharmaabhinav/07774d64f8c02b316414 to your computer and use it in GitHub Desktop.
class PriceCalculator
attr_reader :item_quantities, :item_names
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 set_item_quantities(item_quantities)
@item_quantities = item_quantities
end
def set_item_names(item_names)
@item_names = item_names
end
def initialize
item_quantities = {
milk: 0,
bread: 0,
banana: 0,
apple: 0
}
item_names = []
set_item_quantities(item_quantities)
set_item_names(item_names)
end
def user_input
puts "Please enter all the items purchased separated by a comma"
item_names = gets.chomp.split(',')
set_item_names(item_names)
remove_whitespaces_from_item_names
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 remove_whitespaces_from_item_names
item_names.each do |item_name|
item_name.gsub!(" ","")
end
end
def convert_user_input_to_item_quantities
item_names.each do |item_name|
case item_name
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