Colorize Ruby Terminal Output

Advertisement

Advertisement

Introduction

Coloring your terminal output in a command-line application can make a big difference in readability. This will show you how to format your text in a Ruby application.

We will use the colorize gem, which works in Linux, Mac, and Windows too. Colorize works by adding the ANSI escape characters to set colors.

Install colorize gem

You can install the colorize gem from the terminal using the gem tool.

gem install colorize
gem install win32console  # For Windows only

Alternatively, you could get the source from https://github.com/fazibear/colorize and build the gem yourself, or download the gem from https://rubygems.org/gems/colorize.

Colorize output

The easiest way to colorize output is to simply use the string methods. For example, "some text".red will make red text. There is also a set of .on_* methods like "some text".on_red that will change the background color. You can also chain them together like "text".red.on_blue.bold

# gem install colorize
# gem install win32console  # if on Windows
require 'colorize'

# Basic color output. String is wrapped in color
# and reset color ANSI escape tags.
puts "Blue text".blue

# Wrap part of the output in a color (two options)
puts "This is" + "fancy schmancy".red + "text"
puts "This is #{"fancy schmancy".red} text"

# There's also a bold
puts 'Hi in ' + 'bold!'.bold

# You can combine attributes too
puts 'Bold cyan on blue text'.cyan.on_blue.bold

Note that not all formatting features work in all terminals. For example, bold does not work in all terminals.

Also note that if you do not want the default String class to be modified, you can require 'colorized_string' which will provide a separate ColorizedString class.

List possible formatting options

require 'colorize'

puts String.colors
puts String.modes
puts String.color_samples

Conclusion

You should now know how to easily turn plain terminal output in to nicely formatted colored output using the colorize gem.

References

Advertisement

Advertisement