Reputation: 11
I get the error "NoMethodError: undefined method `<<' for nil:NilClass" when trying to add an object to an empty array. I think it relates to the array being nil instead of empty, and it's not allowing me to append a new object.
The problem occurs with the last line cashier.rule_set.add(apple_rule)
. Not sure if I am implementing the RuleSet class and initializing @rules correctly.
class Rule
attr_reader :sku, :quantity, :price
def initialize(sku, quantity, price)
@sku = sku
@quantity = quantity
@price = price
end
end
class RuleSet
attr_accessor :rules
def initalize()
@rules = []
end
def add(rule)
@rules << rule
end
def rule_for_sku(sku)
@rules.detect { |r| r.sku == sku }
end
end
class Product
attr_accessor :name, :price, :sku
def initialize(name, price)
puts "Added #{name}, which costs $#{price} to available inventory."
@name = name
@price = price
@sku = (rand(100000) + 10000).to_s
end
end
class Cashier
attr_accessor :rule_set
def initialize
@cart = []
@total_cost = 0
@rule_set = RuleSet.new
end
def add_to_cart(product)
puts "Added #{product.name} to your cart."
@cart << product
end
def in_cart
@cart.each_with_object(Hash.new(0)) {|item, counts| counts[item] += 1}
end
def checkout
self.in_cart.each do |item, quantity|
rule = self.rule_set.rule_for_sku(item.sku)
if rule.present? && quantity >= rule.quantity
total_cost += item.price
end
end
end
end
##Testing
#Initialize list of available products and costs
apple = Product.new("apple", 5)
banana = Product.new("banana", 2)
grape = Product.new("grape", 3)
apple_rule = Rule.new(apple.sku, 3, 12)
cashier = Cashier.new
cashier.rule_set.add(apple_rule)
Upvotes: 1
Views: 3445
Reputation: 66343
You have misspelt initialize
in your RuleSet
class (initalize) so that method isn't being called and @rules
is not being set to an empty array.
Upvotes: 3