将数组转成table形式显示

class Table

  attr_accessor :source, :labels

  def display
    source = @source
    labels = @labels
    column_widths = fetch_column_widths(source)
    records = format_rows(source.clone, column_widths)
    div = '-' * records[0].length + "\n"
    label_buffer = ''
    label_buffer = format_cols(labels, column_widths) + "\n" + div if labels
    div + label_buffer + records.join("\n") + "\n" + div
  end

  private
  def tabulate(source)
    source[0].zip(source.length > 2 ? tabulate(source[1..-1]) : source[-1])
  end

  def fetch_column_widths(source)
    d = tabulate(source).map{|x| x.flatten}
    d.map{|x| x.max {|a,b| a.length <=> b.length }.length}
  end

  def format_cols(row, col_widths)
    buffer = '|'
    row.each_with_index do |col, i|
      buffer += ' ' + col.ljust(col_widths[i] + 2) + '|'
    end
    buffer
  end

  def format_rows(source, col_widths)
    source.map {|row| format_cols(row, col_widths)}
  end
end

labels = %w(Name Age Address Code)
contents = [['Bob', '20', '10, High Street','A342'],
  ['Jane', '23', '12/3, Lawn Market Court', 'B34F'],
  ['Bruce', '32', '63, Cotswalds Way', 'F34AD'],
  ['Michael', '49', '1, Hollwood Way', 'E234D'],
  ['Stephanie', '34', '2, Hampton Court','A234']]

table = Table.new
table.source = contents
table.labels = labels
puts table.display

 

示例输出:

 

--------------------------------------------------------
| Name       | Age | Address                  | Code   |
--------------------------------------------------------
| Bob        | 20  | 10, High Street          | A342   |
| Jane       | 23  | 12/3, Lawn Market Court  | B34F   |
| Bruce      | 32  | 63, Cotswalds Way        | F34AD  |
| Michael    | 49  | 1, Hollwood Way          | E234D  |
| Stephanie  | 34  | 2, Hampton Court         | A234   |
--------------------------------------------------------

 

你可能感兴趣的:(Ruby,On,Rails)