How to use Terminal Colors

Using Terminal Colours with Ruby’s Rainbow Gem

Courtney Zhan

--

Recently, I wrote a Ruby text validation script for fun for work adjacent purposes. We used manual auditing previously, which was slow and error prone. The validation script itself was pretty simple and easy to whip up, but as part of the script, I wanted to use colors to highlight errors and warnings. I haven’t used terminal colours before, so this was a fun exercise for me.

In this article, I will walk through how to use Terminal Colors in general and a Ruby gem, Rainbow, that makes terminal coloring easy in Ruby.

Terminal Colors

Terminal colours are created by using ANSI escape sequences, like the following:

# red "hello"
echo "\e[31mhello\e[0m"

# blue "hello"
echo "\e[36mhello\e[0m"

# pink highlight "hello" (with white text)
echo "\e[45mhello\e[0m"

# underlined "hello"
echo "\e[4mhello\e[0m"

For a full list of different effects and options available, see the wikipedia page for ANSI’s Select Graphic Rendition (SGR) parameters.

--

--