Evolve Evolve - 4 months ago 10
Ruby Question

How to output my ruby commandline text in different colours

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 say we start with this..

puts "The following word is blue.. Im Blue!"
puts "The following word is green.. Im Green!"
puts "The following word is red.. Im Red!"


And I get different text I want in different colours I want, You get the idea.

Im using Ubuntu, would I need to change my approach so that the program outputs correctly in diff os?

Answer

I found this article describing a very easy way to write coloured texts to the console. The article describes this little example which seems to do the trick (I took the liberty to improve it slightly):

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

# Actual example
puts 'Importing categories [ ' + green('DONE') + ' ]'
puts 'Importing tags       [' + red('FAILED') + ']'

Best seems to define some of the colours. You can extent the example when you need also different background colours (see bottom of article).

When using Window XP, the author mentions the requirement of a gem called win32console.