Since we mostly work with the command-line, we need our output to be more elegant. Here are the main colors you may need to do so. You can always add to this set.
To understand this code, let's explain it with a diagram
\033 [0; 31m
^ ^ ^
| | |
| | |--------------------------------------- [The color number]
| |-------------------- [The modifier] (ends with "m")
|-- [Escaped character] | 0 - normal
(you can use "\e") | 1 - bold
| 2 - normal again
| 3 - background color
| 4 - underline
| 5 - blinking
Or you can use an external gem called [colorized] for fancier options
gem install colorize
Then just require it in your script
require'colorize'
Overwriting Console Output
It's awesome to have more flexibility in your terminal, and sometimes we need to do more with our scripts.
Overwriting console output makes our applications elegant and less noisy for repeated outputs like counting and loading progress bars.
I've read a how-to about bash Prompt cursor movement and I found it is convenient to have in our scripts. Here's what I've found so far
- Position the Cursor:
\033[<L>;<C>H
Or
\033[<L>;<C>f
puts the cursor at line L and column C.
- Move the cursor up N lines:
\033[<N>A
- Move the cursor down N lines:
\033[<N>B
- Move the cursor forward N columns:
\033[<N>C
- Move the cursor backward N columns:
\033[<N>D
- Clear the screen, move to (0,0):
\033[2J
- Erase to end of line:
\033[K
- Save cursor position:
\033[s
- Restore cursor position:
\033[u
So to test these I created the following PoC
#!/usr/bin/env ruby# KING SABRI | @KINGSABRI(1..3).map do|num|print"\rNumber: #{num}"sleep0.5print ("\033[1B") # Move cursor down 1 line ('a'..'c').map do|char|print"\rCharacter: #{char}"print ("\e[K")sleep0.5print ("\033[1B") # Move cursor down 1 lines ('A'..'C').map do|char1|print"\rCapital letters: #{char1}"print ("\e[K")sleep0.3endprint ("\033[1A") # Move curse up 1 lineendprint ("\033[1A") # Move curse up 1 lineendprint ("\033[2B") # Move cursor down 2 linesputs""
So far so good, but why don't we make these as Ruby methods for more elegant usage? So I came up with the following