If you develop some console application you might want your output be more informative, have different colors for operations or logging purposes. It is possible to do with general ANSI escape codes, which are supported by most common console terminals.
The ASCII escape structure is pretty simple. It begins with “ESC” symbol, which is code 27 in ASCII table. Then “[” symbol. Parameters that goes after “[” symbol are separated by “;” and finally ends with closing sequence: “ESC[0m“.
You can extend basic ruby String class with following code:
class String # colorize functions def red; colorize(self, "\e[1m\e[31m"); end def green; colorize(self, "\e[1m\e[32m"); end def dark_green; colorize(self, "\e[32m"); end def yellow; colorize(self, "\e[1m\e[33m"); end def blue; colorize(self, "\e[1m\e[34m"); end def dark_blue; colorize(self, "\e[34m"); end def pur; colorize(self, "\e[1m\e[35m"); end def colorize(text, color_code) "#{color_code}#{text}\e[0m" ; end end
And sample usage code:
puts "Starting some job...".blue puts "Processing thing 1 [#{"OK".green}]" puts "Processing thing 2 [#{"FAIL".red}]" puts "Oooops! This is a warning!".yellow puts "Another color!".pur
The output:
Nice and useful.

