Ruby类的问题
我很难让它工作。我得到的错误是: “numberstash”中的114:nil的未定义方法“cards”:Nilclass没有方法错误 这是一个21点游戏。我花了几个小时试图修复这段代码,包括编写一系列测试脚本来解决它。然而,我没有运气。这适用于我的测试脚本,但不适用于当前脚本:Ruby类的问题,ruby,Ruby,我很难让它工作。我得到的错误是: “numberstash”中的114:nil的未定义方法“cards”:Nilclass没有方法错误 这是一个21点游戏。我花了几个小时试图修复这段代码,包括编写一系列测试脚本来解决它。然而,我没有运气。这适用于我的测试脚本,但不适用于当前脚本: class Card attr_accessor :suit, :value def initialize(suit, value) @suit = suit @value = value
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
我的问题是,为什么会出现上述错误?在Blackjack中使用player的任何地方,您的意思是@player,例如在Blackjack中: 和Blackjacknumberstash:
@识别实例变量,即attr\u accessor访问的对象。在ruby中,为了测试这一点,编写一个测试断言游戏。实例变量不为零,断言游戏。实例变量==无论定义了多少ect。感谢您的回复Sean。那么你建议我做什么来修复代码呢?对不起,我对Ruby很陌生。感谢您,您只需要了解您在attr_accessor中使用的属性是实例变量,在引用它们时需要加上前缀@。请看一下访问器和实例变量的简要概述。另外,当您编写player=时,您定义的是局部变量,而不是使用setter方法,要使用to setter方法,您可以使用self.player=在本例中,self.player和@player是等效的,因为它们几乎在您使用attr_访问器的任何时候都是等效的。如果访问器执行的操作比仅为变量赋值更复杂,并且在这种情况下,无论如何都不能使用attr\u访问器快捷方式,则只需要使用self版本
@player = Player.new()
puts @player.cards