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

StackOverflow https://stackoverflow.com/questions/4099651

  •  29-09-2019
  •  | 
  •  

Question

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.

Was it helpful?

Solution

Redefine inspect in Puzzle and display only what you want.

For example:

def inspect
  "Puzzle with size #{rows.size}"
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top