Method: CLI::UI::Table.puts_table

Defined in:
lib/cli/ui/table.rb

.puts_table(table, col_spacing: 1, to: $stdout) ⇒ Object

Prints a formatted table to the specified output Automatically pads columns to align based on the longest cell in each column, ignoring the width of ANSI color codes.

Attributes

  • table - (required) 2D array of strings representing the table data

Options

  • :col_spacing - Number of spaces between columns. Defaults to 1

  • :to - Target stream, like $stdout or $stderr. Can be anything with print and puts methods, or under Sorbet, IO or StringIO. Defaults to $stdout

Example

CLI::UI::Table.puts_table([
  ["{{bold:header_1}}", "{{bold:header_2}}"],
  ["really_long_cell",  "short"],
  ["row2",              "row2"]
])

Default Output:

header_1         header_2
really_long_cell short
row2             row2

: (Array[Array] table, ?col_spacing: Integer, ?to: io_like) -> void



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/cli/ui/table.rb', line 35

def puts_table(table, col_spacing: 1, to: $stdout)
  col_sizes = table.transpose.map do |col|
    col.map { |cell| CLI::UI::ANSI.printing_width(CLI::UI.resolve_text(cell)) }.max
  end

  table.each do |row|
    padded_row = row.each_with_index.map do |cell, i|
      col_size = col_sizes[i] #: as !nil # guaranteed to be non-nil
      cell_size = CLI::UI::ANSI.printing_width(CLI::UI.resolve_text(cell))
      padded_cell = cell + ' ' * (col_size - cell_size)
      padded_cell
    end
    CLI::UI.puts(padded_row.join(' ' * col_spacing), to: to)
  end
end