How to output my ruby commandline text in different colours

后端 未结 10 1865
青春惊慌失措
青春惊慌失措 2021-01-30 03:15

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

10条回答
  •  青春惊慌失措
    2021-01-30 03:46

    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.

提交回复
热议问题