简体   繁体   中英

Ruby: NoMethodError: undefined method `<<' for nil:NilClass

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)

你在RuleSet类中initializeRuleSet (initalize),因此没有调用方法,并且@rules没有被设置为空数组。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM