Printing Colored Output Text in Ruby
If you’ve played with the CLIs of various Ruby gems, you’ve probably encountered colored output of strings. I’ve always wondered how to do this myself and tonight I found that ANSI Escape Sequences are the solution to this problem!
If you are wondering how to print colored output as well, I refer you to the following:
From these resources, I was able to write the following code:
#!/usr/bin/env ruby
# Colored Output
def colorize(text, color_code)
"\e[#{color_code}m#{text}\e[0m"
end
def red(text); colorize(text, 31); end
def green(text); colorize(text, 32); end
def yellow(text); colorize(text, 33); end
# Example Code
puts red("ERROR!")
puts green("SUCCESS!")
puts yellow("INFO")