我在尝试将对象添加到空数组时得到错误“NoMethodError:undefined method`<最后一行出现问题不确定我是否正在实现RuleSet类并正确初始化@rules。
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)
最佳答案
您的类(initalize)中有拼写错误的initialize
,因此不会调用该方法,也不会将RuleSet
设置为空数组。
关于ruby-on-rails - Ruby:NoMethodError:nil:NilClass的未定义方法“<<”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29200839/