Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | CLI | Add Color Formatting and Interactivity | Formatting Output with Tables

概要

書籍 Build Awesome Command-Line Applications in Ruby2

Add Color Formatting and Interactivity

いつ表形式の出力を使うか

レコードと列からなる大量のデータを扱う場合。
DBの表データが典型的な例。
他のアプリケーションが利用しやすいフォーマットとしてcsvやTSVなどを提供するのもよいが、
一方で人間向けの表フォーマットも提供すると使いやすいアプリケーションになる。

どうやって表形式の出力を行うか?

terminal-tables gem を利用します。
※日本語の2文字幅には対応していないため、表が崩れる

require 'terminal-table'

rows = []
rows << ['One', 1]
rows << ['Two', 2]
rows << ['Three', 3]
table = Terminal::Table.new(:headings => ['Word', 'Number'], :rows => rows)

puts table
+-------+--------+
| Word  | Number |
+-------+--------+
| One   | 1      |
| Two   | 2      |
| Three | 3      |
+-------+--------+

その他、細かな使い方は後述のリンク先参照