Это потребовало некоторого рефакторинга, чтобы сделать его более идиоматичным Ruby, но результат здесь:
class GameBoard
attr_accessor :cells
def initialize
# Use an instance variable that's local to this particular instance
@cells = [1,2,3,4,5,6,7,8,9]
end
# Define a method that represents this as a string. Note that it's not
# printed, meaning the caller can decide how to use this data.
def to_s
# Use each_slice to pull out rows of 3 and use join to glue them together
# in the right layout.
@cells.each_slice(3).map do |row|
# Each row is converted from [1,2,3] to "1 | 2 | 3"
row.join(' | ')
end.join("\n" + "-" * 10 + "\n")
end
end
class Player
# Players are attached to particular boards with a marker
def initialize marker, board
@marker = marker
@board = board
end
def make_move number
@board.cells[number - 1] = @marker.to_s
end
end
Тогда основной раздел кода теперь выглядит так:
puts "Welcome to Tic-Tac-Toe!"
board = GameBoard.new
bob = Player.new("X", board)
bob.make_move(1)
# Here the .to_s method is called automatically by puts
puts board