【发布时间】:2016-03-31 02:55:15
【问题描述】:
我有一个类Board,它包含来自另一个类Cell 的对象,我想将它们打印为板。我为每个单元格随机分配了'x' 或'o' 的值,我希望它打印'x' 和'o' 的二维数组。
这是我的代码:
class Cell
attr_accessor :cell
def initialize
@cell = ['x', 'o'].sample
end
end
class Board
attr_reader :board
attr_accessor :row
def initialize
@board = Array.new(9)
@row = Array.new(9)
@my_cell = ''
end
def create_row
self.row.map! do |empty_space|
empty_space == nil ? Cell.new : empty_space
end
end
def create_board
self.board.map! do |empty_space|
empty_space == nil ? self.row : empty_space
end
end
def to_s
self.board
end
end
new_board = Board.new
new_board.create_row
new_board.create_board
puts new_board.to_s
当我打印板时,它给了我一个单元格对象坐标的列表。我想不通。
【问题讨论】:
-
对于特定的自定义输出,您可能希望使用某种循环来生成自定义的“漂亮板”。但是,对于快速调试,#inspect 可能很有用。例如:
def to_s; self.board.inspect end -
格式很糟糕,您对
self的使用不一致。有时您使用它,有时您不使用它。