我正在做一项任务,要求我将一些产品加在一起并提供 10% 的折扣,前提是总价超过 60 英镑。我做了以下事情:
class Checkout
def initialize (rules)
@rules = rules
@cart = []
end
def scan (item)
if product == Product.find(item)
@cart << product.clone
#Clone preserves frozen state whereas .dup() doesn't if use would raise a
#NoMethodError
end
end
def total
@cart = @rules.apply @cart
end
def self.find item
[item]
end
co = Checkout.new(Promotional_Rules.new)
co.empty_cart
co.scan(1)
co.scan(2)
co.scan(3)
puts "Total price: #{co.total}"
puts
co.empty_cart
co.scan(1)
co.scan(3)
co.scan(1)
puts "Total price: #{co.total}"
puts
co.empty_cart
co.scan(1)
co.scan(2)
co.scan(1)
co.scan(3)
puts "Total price: #{co.total}"
puts
但是,当我在其中运行时,irb
我得到未定义的变量或方法产品。听起来有点愚蠢,但这应该可行。