首页 文章

Ruby:NoMethodError:nil的未定义方法`<<':NilClass

提问于
浏览
1

在尝试将对象添加到空数组时,我收到错误“NoMethodError:undefined method` <<'for nil:NilClass” . 我认为它与数组有关而不是空,并且它不允许我追加一个新对象 .

最后一行 cashier.rule_set.add(apple_rule) 出现问题 . 不确定我是否正在实现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)

1 回答

  • 3

    您在 RuleSet 类(initalize)中有拼错 initialize ,因此未调用该方法且 @rules 未设置为空数组 .

相关问题