开发者

In Ruby, can I limit the amount of drilling down a object does when displaying itself in irb or when using .inspect?

开发者 https://www.devze.com 2023-01-23 07:35 出处:网络
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:

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.


Redefine inspect in Puzzle and display only what you want.

For example:

def inspect
  "Puzzle with size #{rows.size}"
end
0

精彩评论

暂无评论...
验证码 换一张
取 消