在 Ruby 中,我可以限制对象在 irb 中显示自身或使用 .inspect 时向下钻取的数量吗?
我正在编写一个用于解决数独谜题的类,该类具有一些二维数组,其中包含指向指向这些二维数组的 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 是否有一种方法只返回该数组的浅层表示,因为它的所有指针最终都指向自身。
I'm writing a class for solving sudoku puzzles that has some two dimensional arrays which contain pointers to Cells
that point back to these two dimensional arrays. Something like this:
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
The problem is that when I do something like:
p = Puzzle.new
in irb
, irb freezes up. I've modified some of the code now so it doesn't do that but now if I do:
irb> p.rows
=> TONS OF SHIT GETS RETURNED
it outputs tons and tons of nested pointers and takes about 20 seconds to return to the irb
prompt. A lot of this has to do with some infinite pointers i.e.:
p.rows[0][0].row[0].row[0].row[0]....
So I'm wondering if there is a way for Ruby to just return a shallow representation of this array since all of its pointers end up pointing back to itself.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
重新定义 Puzzle 中的检查并仅显示您想要的内容。
例如:
Redefine inspect in Puzzle and display only what you want.
For example: