How can I make the puts commands I output from a commandline based ruby program colour? I would appreciated any references to how I call each different colour also.
Lets
For a quick and dirty solution you can just embed ASCII colour codes in your strings (\e[XXm sets the colour to be used from now on to XX and \e[0m reset the colour to normal):
puts "The following word is blue.. \e[34mIm Blue!\e[0m"
puts "The following word is green.. \e[32mIm Green!\e[0m"
puts "The following word is red.. \e[31mIm Red!\e[0m"
ASCII codes also support things like underlining, blinking, and highlighting of text.
There also seems to be a helper library available that deals with the actual ASCII codes for you.
Edit: regarding the different platforms: you shouldn't have any trouble using ASCII codes on unix machines, but windows, AFAIK, doesn't support them out of the box. Fortunately there's a win32console gem that seems to fix this.
You can use the following snippet (found on the page Veger linked to) to load the win32console library only on windows:
begin
require 'Win32/Console/ANSI' if PLATFORM =~ /win32/
rescue LoadError
raise 'You must gem install win32console to use color on Windows'
end
Use Colorize gem! Check it out:
https://github.com/fazibear/colorize
Installation:
sudo gem install colorize
usage:
require 'colorize'
puts "I am now red.".red
puts "I am now blue.".green
puts "I am a super coder".yellow
I find the Colored gem to be the easiest and cleanest to use.
puts "this is red".red
puts "this is red with a blue background (read: ugly)".red_on_blue
puts "this is red with an underline".red.underline
puts "this is really bold and really blue".bold.blue
logger.debug "hey this is broken!".red_on_yellow
use escape sequence \033
instead of \e
as it is 100% posix compatible and will work on bsd-ish (e.g. osx) systems as well. the latter is a gnu extension.