我正在做一项任务,要求我一起添加一些产品,并提供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
中运行时,我得到未定义的变量或方法产品。听起来有点蠢,但这应该有效。
答案 0 :(得分:1)
你使用了太多的等号
def scan (item)
# if product == Product.find(item)
if product = Product.find(item) # <--- should be this
@cart << product.clone
#Clone preserves frozen state whereas .dup() doesn't if use would raise a
#NoMethodError
end
end
当然,那么你会得到一个不同的错误,因为find
上Product
还不存在......我认为你在这里定义了这个错误:
def self.find item # self should be changed to Product
[item]
end
然后,apply
的{{1}}不存在错误...
调试这些错误的最佳方法之一是遵循堆栈跟踪。因此,对于最后一个错误,我收到以下消息:
Promotional_Rules
这基本上是说test.rb:53:in `total': undefined method `apply' for #<Promotional_Rules:0x007f94f48bc7a8> (NoMethodError)
from test.rb:72:in `<main>'
,line 53
,apply
尚未定义@rules
Promotional_Rules
的实例Promotional_Rules
。查看apply_to_item
课程,您已明确将该方法定义为apply
而非{{1}}。如果您继续关注并修复这样的兔子踪迹以获得堆栈跟踪,您将能够轻松调试您的程序!