我试图让一个方法启动另一个类的多个实例。
class Players
def initialize(players)
@players = players
end
def generate_boards
@players.each do |player|
board = BingoBoardGenerator.new
player = BingoBoard.new(player, board.generate)
p player
end
end
end
players = ["Nick","Jiyoon","Mae","Lawson","Matthew"]
plays = Players.new(players)
plays.generate_boards
p player
显示正确创建了五个BingoBoard
个实例,但我不确定如何访问它们(或它们的位置)。有关如何调用这些实例的任何帮助?通常我会这样做:
nick = BingoBoard.new("Nick", board.generate)
nick.board
但是当我将它们全部实例化时,我不知道如何设置/访问它们的实例名称。
答案 0 :(得分:0)
如user2864740所示,您可以使用:map
代替:each
来返回BingoBoard
个实例的数组。如果要存储这些实例以便稍后使用,可以使用memoization,如下所示。第一次调用:bingo_board_instances
时,将生成电路板并设置实例变量@bingo_board_instances
,以便将来调用:bingo_board_instances
不会导致生成新电路板。
class Players
def initialize(players)
@players = players
end
def generate_boards
@players.map do |player|
board = BingoBoardGenerator.new
BingoBoard.new(player, board.generate)
end
end
def bingo_board_instances
@bingo_board_instances ||= generate_boards
end
end
虽然上面的代码运行得很好,但我认为更直观的解决方案是拥有Player
类(而不是Players
),然后传入Player
个实例的数组初始化BingoBoardGenerator
时。通过这种方法,您可以为每个单独的玩家设置一个实例变量,并创建一个属于该玩家的独特棋盘:
class BingoBoardGenerator
def initialize(args)
#dynamically set instance vars to handle n number of players
args.fetch(:players).each_with_index do |player,index|
instance_variable_set("@player_#{index+1}",player)
end
end
def generate_boards
instance_variables.map do |player|
player = instance_variable_get(instance_var)
#you will need to implement :generate_bingo_board on player...I would suggest using memoization so you can store the player's board for later retrieval
player.generate_bingo_board
end
end
end
#I have no idea what your implementation looks like...
b = BingoBoardGenerator.new(players: [Player.new("Jen"),Player.new("Phil"),Player.new("Mary"),Player.new("Bert")])
b.generate_boards
这将允许您更好地封装可能属于各个玩家的数据,包括向每个Player
实例询问其:board
的能力。