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

I am writing a class for solving sudoku puzzles that has several two-dimensional arrays that contain pointers to Cellsthat point to these two-dimensional arrays. Something like that:

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. I changed some of the code now, so it doesn’t, but now if I do:

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

it displays tons and tons of nested pointers and takes about 20 seconds to return to the invitation irb. Much has to do with some infinite pointers, namely:

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

, , Ruby , .

+3
1

, .

:

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

Source: https://habr.com/ru/post/1773106/


All Articles