Cover by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

21.9. Changing Text Color

Problem

You want to display multicolored text on the console.

Solution

The simplest solution is to use HighLine. It lets you enclose color commands in an ERb template that gets interpreted within HighLine and printed to standard output. Try this colorful bit of code to test the capabilities of your terminal:

	require 'rubygems'
	require 'highline/import'

	say(%{Here's some <%= color('dark red text', RED) %>.})
	say(%{Here's some <%= color('bright red text on a blue background',
	                                RED+BOLD+ON_BLUE) %>.})
	say(%{Here's some <%= 
color('blinking bright cyan  
text', CYAN+BOLD+BLINK) %>.})
	say(%{Here's some <%= GREEN+UNDERLINE %>underlined dark green text<%=CLEAR%>.})

Some of these features (particularly the blinking and underlining) aren't supported on all terminals.

Discussion

The HighLine#color method encloses a display string in special command strings, which start with an escape character and a left square bracket:

	HighLine.new.color('Hello', HighLine::GREEN)
	# => "\e[32mHello\e[0m"

These are ANSI escape sequences. Instead of displaying the string "\e[32m", an ANSI-compatible terminal treats it as a command: in this case, a command to start printing characters in green-on-black. The string "\e[0m" tells the terminal to go back to white-on-black.

Most modern Unix terminals support ANSI escape sequences, including the Mac OS X terminal. You should be able to get green text in your irb session just by calling puts "\e[32mHello\e[0m" (try it!), but HighLine makes it easy ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required