包含数组的对象为nil

时间:2017-09-10 22:14:34

标签: ruby class

我有一个类Deck代表81个卡的数组但是当我尝试在数组中的任何卡上使用我的getter函数时,它会给出错误undefined method getColor for nil:NilClass (NoMethodError),我认为这意味着所有内容都在我的数组等于nil

我试图弄清楚如何设置我的Deck类,以便我可以通过使用getCard函数返回任何卡,然后使用卡getter方法然后获取所有值个人卡。

class Card  
    def initialize id, symbol, color, shading, number
        @cardId = id #0-80 unique for each indivdual card in the deck
        @cardSymbol = symbol # 0 = diamond 1 = squigly 2 = oval
        @cardColor = color # 0 = green 1 = blue 2 = pink
        @cardShading = shading # 0 = none 1 = lines 2 = solid
        @cardNumber = number #number of the symbols on the card
    end

    def getId
        @cardId
    end

    def getSymbol
        @cardSymbol
    end

    def getColor
        @cardColor
    end

    def getShading
        @cardShading
    end

    def getNumber
        @cardNumber
    end

end

class Deck

    def initialize
        @deck = Array.new(81)
        @cardDealt = Array.new(81)
    end

    def AddCardsToDeck  
        cardId = 0
        symbol = 0
        color = 0
        shading = 0
        number = 0
        while cardId < 80
            if symbol > 2
                symbol = 0
                color = color + 1
            elsif color > 2
                color = 0
                shading = shading + 1
            elsif shading > 2
                shading = 0
                number = number + 1
            else
                symbol = symbol + 1
            end 
            card = Card.new(cardId, symbol, color, shading, number)
            cardId = cardId + 1
            @deck[cardId] = @card
        end 
    end

    def getCard cardId
        @deck[cardId]
    end
end

setDeck = Deck.new
setDeck.AddCardsToDeck
card0 = setDeck.getCard(0)
puts "Color is #{card0.getColor}"

1 个答案:

答案 0 :(得分:2)

card = Card.new(cardId, symbol, color, shading, number)
cardId = cardId + 1
@deck[cardId] = @card

是问题所在。注意如何在第一行中设置局部变量card,而在第三行中使用未初始化的实例变量@card。这会将所有条目设置为nil

另一个问题是在将cardId用作索引之前递增{{1}}。这会将卡0设置为插槽1等。经典的“一次性”错误。