Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 426
Evolve Avatar asked Jan 15 '10 07:01

Evolve


Video Answer


2 Answers

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.

like image 154
Veger Avatar answered Sep 30 '22 15:09

Veger


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  
like image 28
Mark Carey Avatar answered Sep 30 '22 16:09

Mark Carey