Is there a Ruby module for colorizing strings in a Linux terminal?
-
4I won't post an answer, so I don't revive this, but there's a nifty gem called "colored." it's as simple as: `"string".red` to get red text. [More info](http://rubydoc.info/gems/colored/1.2/frames) :D – omninonsense Sep 04 '11 at 00:31
-
You can check this as well as there are options to do that without installing another Gem: [Colorized Ruby output](http://stackoverflow.com/questions/1489183/colorized-ruby-output) – Adriano P Jul 18 '12 at 16:21
5 Answers
I prefer the Rainbow gem since it also supports Windows if the win32console gem has been installed.
You can use it like this:
puts "some " + "red".color(:red) + " and " + "blue on yellow".color(:blue).background(:yellow)

- 30,738
- 21
- 105
- 131

- 1,550
- 2
- 17
- 15
All you have to do is start with "\e[##m"
and end with "\e[0m"
Just replace the ## with the color number. Examples are:
31:Red
32:Green
33:Yellow
34:Blue
35:Magenta
36:Teal
37:Grey
1:Bold (can be used with any color)
Here is a Ruby script to show all the terminal colors. Download it or run the code below.
def color(index)
normal = "\e[#{index}m#{index}\e[0m"
bold = "\e[#{index}m\e[1m#{index}\e[0m"
"#{normal} #{bold} "
end
8.times do|index|
line = color(index + 1)
line += color(index + 30)
line += color(index + 90)
line += color(index + 40)
line += color(index + 100)
puts line
end

- 30,738
- 21
- 105
- 131

- 3,453
- 3
- 30
- 34
Using String class methods like:
class String
def black; "\033[30m#{self}\033[0m" end
def red; "\033[31m#{self}\033[0m" end
def green; "\033[32m#{self}\033[0m" end
def brown; "\033[33m#{self}\033[0m" end
def blue; "\033[34m#{self}\033[0m" end
def magenta; "\033[35m#{self}\033[0m" end
def cyan; "\033[36m#{self}\033[0m" end
def gray; "\033[37m#{self}\033[0m" end
end
and usage:
puts "This prints green".green
puts "This prints red".red

- 1,987
- 2
- 15
- 9
I am a big fan of the Ruby colorize gem, which I recently downloaded. Once you download and include it into your program, you can add
.colorize(:blue)
to the end of any string. You can use most colors, including preceding the color by light_ like so:
.colorize(:light_blue)
you can also do background colors, EG:
puts "mytext".colorize(:background => :green
colorized underlines, EG:
puts "mytext".on_blue.underline
Or use HTML-like tags for it as well
puts <blue> "text text text" </blue>
For the colorize GitHub, go to The colorize GitHub.
You can install the colorize gem by typing
gem install colorize
into your terminal, command prompt, whatever. Then put this into your file before you put in the uses of it.
For example:
require 'rubygems'
require 'colorize'
puts "mytext".colorize(:red)
But not:
puts "mytext".colorize(:red)
require 'rubygems'
require 'colorize'
The require statements must be in the program in lines before you use the gem.

- 30,738
- 21
- 105
- 131