I am writing a small Ruby script that will run in a CLI.
To improve the interface, I need to would love to add color/boldness to some elements that I output.
Is that doable? If so, and I am almost sure this is, how?
On many terminals (but not Windows), you can use an a sequence like this: "\e[#{code}m", where the codes are based on these tables. The codes must be separated by a semicolon if using more than one. The major codes are:
1 Bold Intensity
4 Underline
5 Slow blink
6 Fast blink
22 Normal Intensity
Foreground 3X
Background 4X
Where X is:
-----------
0 Black
1 Red
2 Green
3 Yellow
4 Blue
5 Magenta
6 Cyan
7 White
So, for example, for slowly blinking, bold green text on a blue background, you would use "\e[5;1;32;44mWOW!\e[0m". The \e[0m resets everything to the terminal default.
There is a gem called rainbow that makes it really easy to style your terminal output.
sudo gem install rainbow
After installing it you can do stuff like:
puts 'some text'.underline
Dear Ruby folks! I prefer to find the default integrated support available within Ruby. Here I've found a few, which may work without installing any gem:
def red(mytext); "\e[31m#{mytext}\e[0m"; end
def light_red(mytext); "\e[1;31m#{mytext}\e[0m"; end
def green(mytext); "\e[32m#{mytext}\e[0m"; end
def light_green(mytext); "\e[1;32m#{mytext}\e[0m"; end
def yellow(mytext); "\e[1;33m#{mytext}\e[0m"; end
def blue(mytext); "\e[34m#{mytext}\e[0m"; end
def light_blue(mytext); "\e[1;34m#{mytext}\e[0m"; end
puts red("hello world. I don't need no color.")
puts light_red("hello world. I don't need no color.")
puts green("hello world. I don't need no color.")
puts light_green("hello world. I don't need no color.")
puts blue("hello world. I don't need no color.")
puts light_blue("hello world. I don't need no color.")
puts yellow("hello world. I don't need no color.")
It works with both puts and print.