我有这堂课:
class Player
attr_accessor :card_pile, :name
def initialize
@name = name
@bust = false
@card_pile = []
end
def bust?
return @cards.inject(:+) > 21
end
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
@players.each do |each_player|
@name = Player.new
while true
while @name.card_pile.length < 2 do
new_card = Card.new
@name.card_pile.push(new_card.value)
end
puts(@name.card_pile)
print @name, "'s turn" "\n"
目前,这将打印出#<Player:0x007fc14984a4b0>'s turn
而不是Rich's turn
为什么会这样?我以为我在Player类中创建了一个实例变量,然后实例化了这个类@name = Player.new
,然后可以从这里引用它?
答案 0 :(得分:-1)
这将有助于
def playing_game
puts 'How many players are playing?'
players_amount = gets.chomp.to_i
players_names = (0...players_amount).map do
puts ("What is the players name? ")
gets.chomp
end
players_names.each do |player_name|
player = Player.new(player_name)
while player.card_pile.length < 2 do
new_card = Card.new
player.card_pile.push(new_card.value)
end
puts player.card_pile
puts "#{player.name}'s turn"
end
end
UPD:
@name
和@players
)。在此代码中,您将遍历玩家名称
@ players.each do | each_player |
=&GT;
players_names.each do |player_name|
在
的背景下@name = Player.new
name是一个Player实例 创建具有给定名称的播放器将其传递给初始化器:
player = Player.new(player_name)
然后在Player实例上调用您之前创建的名称
puts "#{player.name}'s turn"