尝试实现一种打折产品价格的方法 (Ruby)

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

我有这个产品列表,我想实现一种方法来根据用户购买的多少来更改项目的价格。所以我创建了 3 个产品:

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

然后我有这样的逻辑,对于商品 2,用户可以以 1 的价格购买 2 件商品,然后对于商品 2,如果用户购买 3 件或更多商品,则每件商品可享受 1 美元的折扣。

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}"

显然逻辑不成立。有人对此有任何想法吗?我想做一个 class 结帐,其中我有一个方法 pricing_rules 定义了所有价格规则但不知道如何实现它。


考虑到您正在尝试实现

的逻辑
  1. Item1 用户可以以 1 的价格购买 2 件商品
  2. 商品 2 如果用户购买 3 件或更多件,每件可享受 1 美元的折扣。
  3. 商品 3 无折扣

这是所需的代码:

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}"

希望对您有所帮助。