3

我正在编写一个用于解决数独难题的类,该类具有一些二维数组,其中包含指向Cells该点的指针返回到这些二维数组。像这样的东西:

def class Sudoku
  attr :rows, :columns, :blocks

  def initialize
    # build each of the rows, columns, and blocks with a 9x9 map of Cells
  end
end

def class Cell
  attr :value, :row, :column, :block

  def initialize(row, column, block, value)
    # set each pointer to its parent row, column and block etc
  end
end

问题是当我做类似的事情时:

p = Puzzle.new

irb,irb 冻结。我现在修改了一些代码,所以它不会这样做,但现在如果我这样做:

irb> p.rows
=> TONS OF SHIT GETS RETURNED

它输出大量嵌套指针,并需要大约 20 秒才能返回irb提示。其中很多与一些无限指针有关,即:

p.rows[0][0].row[0].row[0].row[0]....

所以我想知道Ruby是否有办法只返回这个数组的浅表表示,因为它的所有指针最终都指向自身。

4

1 回答 1

2

在 Puzzle 中重新定义检查并仅显示您想要的内容。

例如:

def inspect
  "Puzzle with size #{rows.size}"
end
于 2010-11-04T18:01:42.800 回答