Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

command line - 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?

question from:https://stackoverflow.com/questions/2070010/how-to-output-my-ruby-commandline-text-in-different-colours

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...