-1
我無法正常工作。我得到的錯誤是:Ruby - nilClass的問題
114 in'numberstash':未定義的方法'cards'爲零:Nilclass(無方法錯誤)。
這是一個二十一點遊戲。我花了幾個小時試圖修復這些代碼,包括製作一堆測試腳本來解決這個問題。但是,我沒有運氣。這工作對我的測試腳本,但它不會對當前的腳本工作:
class Card
attr_accessor :suit, :value
def initialize(suit, value)
@suit = suit
@value = value
end
def to_s
"#{value} of #{suit}"
end
end
class Deck
attr_accessor :cards
def initialize(number_of_decks)
@cards = []
num = number_of_decks
counter = 0
while counter < num
['H','C', 'S', 'D'].product(['2','3','4','5','6','7','8','9','10','J','K','Q','A']).each do |arr|
@cards << Card.new(arr[0], arr[1])
end
counter += 1
end
end
end
class Player
attr_accessor :cards, :testvalue
def initialize
@cards = []
end
end
class Dealer
attr_accessor :cards
@cards = []
end
class Blackjack
attr_accessor :deck, :player, :dealer
def calculate arr
new = arr.map { |e| e[1] }
sum = 0
ace = 0
new.each { |value|
if value == 'A'
sum += 1
ace = 1
elsif value.to_i == 0
sum += 10
else
sum += value.to_i
end
}
if ace = 1 && sum + 10 <= 21
ace = 0
sum = sum + 10
end
end
def initialize
deck = Deck.new(4)
#@deck = @deck.shuffle
player = Player.new()
dealer = Dealer.new()
end
def dealcards
#puts 'dealcards'
#player.cards << deck.cards.pop
#dealer.cards << deck.cards.pop
end
def start
#dealcards
#player_turn
#dealer_turn
#compare?
#play again?
numberstash
end
def numberstash
#player.cards << deck.cards.pop
puts player.cards
#dealer.cards << deck.cards.pop
end
end
game = Blackjack.new()
game.start
我的問題是,爲什麼我收到上面提到的錯誤?
隨着它進入ruby,測試這個,寫一個測試斷言game.instance_variables not_nil,assert game.instance_variables == #however許多你定義)等等。 – darethas
謝謝你回覆肖恩。那麼你建議我如何修復代碼?對於Ruby來說,我很抱歉。謝謝 –
只需要理解你用'attr_accessor'使用的屬性是實例變量,並且在引用它們時需要用'@'作爲前綴。看看[這個答案](http://stackoverflow.com/a/4371458/131226)簡要介紹訪問器和實例變量。 –