Pretty printing a Matrix

I am trying to implement pretty_print for my Matrix class. Currently I have this:

def pretty_print(pp) : Nil
  pp.list("[", self.rows, "]") do |a|
    pp.group do
      a.pretty_print(pp)
    end
  end
end

Which works fine for large matrices, but with smaller ones it prints all the columns in one row.
i.e pp Matrix.identity(2) would print [[1, 0], [0, 1]].

I want it to always do what it does with larger matrices and break on rows.

pp Matrix.identity(10)
# => [[1, 0, 0, 0, 0, 0, 0, 0, 0],
#     [0, 0, 0, 0, 0, 0, 0, 0, 0],
#     [0, 0, 1, 0, 0, 0, 0, 0, 0],
#     [0, 0, 0, 1, 0, 0, 0, 0, 0],
#     [0, 0, 0, 0, 1, 0, 0, 0, 0],
#     [0, 0, 0, 0, 0, 1, 0, 0, 0],
#     [0, 0, 0, 0, 0, 0, 1, 0, 0],
#     [0, 0, 0, 0, 0, 0, 0, 1, 0],
#     [0, 0, 0, 0, 0, 0, 0, 0, 1]]

Obviously this is in-built behavior with pretty_print for larger Arrays, so it shouldn’t be too hard replicate, but I don’t know enough about pretty_print and the documentation isn’t overly clear.

1 Like