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?
Check out the following libraries:
http://www.gnu.org/software/ncurses/ncurses.html
https://github.com/JEG2/highline
http://coderay.rubychan.de/
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.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):
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:
Use Colorize gem! Check it out:
https://github.com/fazibear/colorize
Installation:
usage:
I've created something like this:
Now you can just use another method of String:
To know all the colors just execute this:
Thought I'd add another solution as it does things a little differently and includes more colour codes:
First some examples...
Using method chaining:
Using the
style
method and applying multiple attributes:This can be used to store style attributes in some manner to apply later:
I've given a few more examples on this gist I created and expanded the code to include refinements so that modifications to String are scoped.
This is the basic code: