Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

inspect

irb

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.

like image 995
aarona Avatar asked Jan 29 '26 10:01

aarona


1 Answers

Redefine inspect in Puzzle and display only what you want.

For example:

def inspect
  "Puzzle with size #{rows.size}"
end
like image 109
valodzka Avatar answered Feb 01 '26 01:02

valodzka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!