Terminal Table基于 Ruby 的表格生成器
Terminal Table 是一个用 Ruby 编写的简单好用、功能丰富的表格生成器,支持 ASCII 和 Unicode 格式。
用例
构建表格需要基本的阵列信息:
rows = [] rows << ['One', 1] rows << ['Two', 2] rows << ['Three', 3] table = Terminal::Table.new :rows => rows # > puts table # # +-------+---+ # | One | 1 | # | Two | 2 | # | Three | 3 | # +-------+---+
可以给构造函数一个 block,该 block 可以生成 Table 对象,也可以计算实例:
table = Terminal::Table.new do |t| t.rows = rows end table = Terminal::Table.new do self.rows = rows end
一行一行地添加:
table = Terminal::Table.new do |t| t << ['One', 1] t.add_row ['Two', 2] end
在行之间添加分隔符:
table = Terminal::Table.new do |t| t << ['One', 1] # Using << (push) as an alias for add_row t << :separator # Using << with :separator as an alias for add_separator t.add_row ['Two', 2] t.add_separator # Note - this version allows setting the separator's border_type t.add_row ['Three', 3] end # > puts table # # +-------+---+ # | One | 1 | # +-------+---+ # | Two | 2 | # +-------+---+ # | Three | 3 | # +-------+---+
定义表格样式
table = Terminal::Table.new :headings => ['Word', 'Number'], :rows => rows, :style => {:width => 80} # > puts table # # +--------------------------------------+---------------------------------------+ # | Word | Number | # +--------------------------------------+---------------------------------------+ # | One | 1 | # | Two | 2 | # | Three | 3 | # +--------------------------------------+---------------------------------------+
评论