class Player
attr_accessor :card_pile
def initialize
@bust = false
@card_pile = []
end
def bust?
return @cards.inject(:+) > 21
end
end
我有这个Player类并且已经初始化了card_pile变量
class Game
def initialize
@players = []
end
def playing_game
puts "How many players are playing? "
players_amount = gets.chomp.to_i
(0...players_amount).each do
puts ("What is the players name? ")
name = gets.chomp
@players.push(name)
end
puts @players
player = Player.new
player.initialize
while @card_pile.length < 2 do
new_card = Card.new
@card_pile.push(new_card.value)
end
end
我希望在下面的while循环中使用这个变量。为什么不能以我希望的方式访问它?
错误信息是:``playing_game':私有方法initialize' called for #<Player:0x007fda53073f48 @bust=false, @card_pile=[]> (NoMethodError)
答案 0 :(得分:1)
initialize
创建类的新实例时,会自动调用 Player.new
。您目前没有任何参数传入您的initialize方法,但您已将实例变量card_pile
设置为attr_accessor
,因此您可以执行此操作:
player = Player.new
while player.card_pile.length < 2 do
new_card = Card.new
player.card_pile.push(new_card.value)
end