Consider the following code
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
If I run the code as is I get a noMethodError on has_key? but if I create the Hash in initialize everything works. Why can’t I create the Hash at the declaration?
When you define an instance variable in the class body, it’s a class instance variable defined on
CheckOut, which is an instance ofClass, and doesn’t exist in an instance ofCheckOut. Instead you need to define the instance variables in yourinitializeas you’ve found (sinceinitializeruns in the context of the newCheckOutinstance):Here’s a quick example illustrating this further:
This also shows that all instance variables default to
nil, even if they’ve never been referenced before. This is why your error is aNoMethodError for nil:NilClassand not aNameError.