Format Your Output in Terminal with Ruby
Ruby命令行格式化输出
If we want to output content in the command line, generally speaking, Ruby basic methods are enough, such as puts
, print
, and sprintf
; but if we want to output color in the terminal, table, and progress bar, etc., it will be more difficult to achieve.
Here, I want to share gems that I feel good using in this situation:
Color output (based on ANSI): rainbow
Table output: terminal-table
Large composite (contains color, table, and progress bar): formatador
Rainbow
The underlying mechanism for outputting colored text in the console comes from ANSI escape sequences, e.g. to output the word Red in red, it should be "\e[31mRed\e[0m"
.
puts "\e[31mRed\e[0m"
=> Red
It's too much trouble to organize this escape sequence by ourselves, but fortunately rainbow can help us do this, using other is also very simple (as follows), foreground color, background color, underline and other formats are supported, and more features refer to his README rainbow
Rainbow("hello").red
# => "\e[31mhello\e[0m" ("hello" if not on TTY)
Rainbow("hola!").blue.bright.underline
# => "\e[34m\e[1m\e[4mhola!\e[0m"
Terminal-table
The use of terminal-table is also fairly simple and straightforward, and adding table headers and setting alignment is easy: ``
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 |
# +-------+--------+
formatador
formatador seems to me to be a large and comprehensive formatting tool, and is straightforward to use.
Color output
Formatador.display_line('[green]Hello World[/]')
Table
table_data = [
{ :name => "Joe", :food => "Burger" }
{ :name => "Bill", :food => "French fries" }
]
Formatador.display_table(table_data)
#=> +------+--------------+
# | name | food |
# +------+--------------+
# | Joe | Burger |
# +------+--------------+
# | Bill | French fries |
# +------+--------------+
Progress bar
total = 1000
progress = Formatador::ProgressBar.new(total)
1000.times do
sleep 0.01
progress.increment
end
#=> 978/1000 | ************************************************* |