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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With