Terminal Table基于 Ruby 的表格生成器

联合创作 · 2023-09-30 15:59

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                                     |
# +--------------------------------------+---------------------------------------+
浏览 8
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报