Search code examples
rubymethodsinstance-variables

Trying to implement a method to discount products' prices (Ruby)


I have this list of products, and I would like to implement a method to change the price of the items according to how much the user buys. So I create 3 products:

item1 = Item.new("item1", 5.00)
item2 = Item.new("item2", 10.00)
item3 = Item.new("item3", 8.00)

Then I have this logic that says for item2 the user can buy 2 items for the price of 1, then for item 2 if the user buys 3 or more there is 1$ discount per unit.

user_input = nil
item_list = []

until user_input == "stop"
  puts 'Which item would you like to add? (type "stop" to exit purchase)'
  user_input = gets.chomp
  if user_input == "item1"
    if item_list.count("item1") % 2 == 0
      item1.price = 2.5
    else
      discount_item1 = item_list.count("item1") - 1
      item1.price = (discount_item1 * 2.5) + 5.00
    end
    item_list << item1
  end

  if user_input == "item2"
    if item_list.count("item2") >= 3
      tshirt.price = 19.00
    else
      tshirt.price = 20.00
    end
    item_list << item2
  end

  if user_input == "item3"
    item_list << item3
  end
end


print "Items:"
sum = item_list.inject(0) do |sum, item|
  print " #{item.name},"
  sum += item.price
end
puts "Total: #{sum}"

Obviously the logic doesn't work. Anyone has any thoughts on doing it? I was thinking do a class Checkout in which I have a method pricing_rules that define all the rules for prices but don't know how to implement it.



Solution

  • Considering the fact that you are trying to implement the logic that

    1. Item1 the user can buy 2 items for the price of 1
    2. Item2 if the user buys 3 or more there is 1$ discount per unit.
    3. Item3 no discount

    Here is the required code :

    user_input = nil
    item_list = []
    item1_count = 0
    item2_count = 0
    item3_count = 0
    until user_input == "stop"
      puts 'Which item would you like to add? (type "stop" to exit purchase)'
      user_input = gets.chomp
      if user_input == "item1"
        item1_count += 1
      elsif user_input == 'item2'
        item2_count += 1
      elsif user_input == "item3"
        item3_count += 1
        item_list << Item.new('item3', 8)
      end
    end
    
    if item1_count.even?
      item1_count.times {item_list << Item.new('item1', 2.5)}
    else
      (item1_count-1).times {item_list << Item.new('item1', 2.5)}
      item_list << Item.new('item1', 5)
    end
    
    item2_price = (item2_count >= 3) ? 19 : 20
    item2_count.times {item_list << Item.new('item2', item2_price)}
    
    
    print "Items:"
    sum = item_list.inject(0) do |sum, item|
      print " #{item.name},"
      sum += item.price
    end
    puts "Total: #{sum}"
    

    Hope this helps.