考虑以下代码
class CheckOut
@rules
@total = 0
@basket = Hash.new
def initialize(rules, discounts)
@total=0
#if i use the line below everything is ok.
#@basket = Hash.new
@rules = rules
end
def scan sku
price = @rules[sku]
if @basket.has_key?(sku) #I get NoMethodError: undefined method `has_key?' for nil:NilClass
@basket[sku] += 1
else
@basket[sku] = 1
end
@total += price
end
def total
@total
end
end
如果我按原样运行代码,我会在 has_key 上得到 noMethodError?但是如果我在初始化时创建哈希,一切正常。为什么我不能在声明时创建哈希?