Ruby `add_item': nil:NilClass 的未定义方法 `>' (NoMethodError)

Ruby `add_item': undefined method `>' for nil:NilClass (NoMethodError)

Ruby 的新手。接收错误:

item_container.rb:14:in add_item': undefined method<' for nil:NilClass (NoMethodError)

我知道这个错误是什么意思,但不明白是什么原因导致的以及如何解决?在制作 ClassMethodsInstanceMethods 和添加回调之前一切正常。

#item_container.rb
module ItemContainer

    module ClassMethods

        def min_price
            100 
        end

    end

    module InstanceMethods

        def add_item(item)
            unless item.price < self.class.min_price #<----- error line
                @items.push item
            end
        end

    end

    def self.included(base)
        base.extend ClassMethods
        base.class_eval do 
            include InstanceMethods
        end
    end

end
#init.rb
require_relative "item_container"
require_relative "cart"
require_relative "order"
require_relative "item"
require_relative "virtual_item"
require_relative "real_item"

item1 = VirtualItem.new({ :price => 10, :name => "car" })
item2 = RealItem.new({ :price => 100, :weight => 20, :name => "kettle" })
item3 = RealItem.new({ :price=> 10, :weight => 100, :name => "dishwasher" })

cart = Cart.new
cart.add_item item1
cart.add_item item2
class Item

    @@discount = 0.05

    def self.discount
        if Time.now.month == 2
            @@discount + 0.1
        else
            @@discount 
        end
    end

    def initialize(options={})
        @real_price     = options[:price]
        @name               = options[:name]
    end

    attr_accessor :real_price
    attr_reader   :name

    def info    
        yield(price)
        yield(name)
    end

    def price
        (@real_price - @real_price * self.class.discount) + tax if @realprice
    end

    private

        def tax
            type_tax = if self.class == VirtualItem
                1
            else
                2
            end
            cost_tax = if @real_price > 5 
                @real_price * 0.2
            else
                @real_price * 0.1
            end
            cost_tax + type_tax
        end

end


好了:

def price
  (@real_price - @real_price * self.class.discount) + tax if @realprice
end

这里打错了,应该是if @real_price