How to output my ruby commandline text in differen

2019-03-08 02:22发布

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?

10条回答
2楼-- · 2019-03-08 03:11

My suggestion: The paint gem. It does not enforce string extensions and supports 256-colors (with fall-back mode for non-256-color terminals).

Usage:

puts Paint["I'm blue!", :blue]
puts Paint["I'm dark blue if your terminal supports it!", "#000044"]
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-03-08 03:16

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.

查看更多
疯言疯语
5楼-- · 2019-03-08 03:21

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 
查看更多
登录 后发表回答