How can I use Ruby to colorize the text output to a terminal? [closed]
Colorize is my favorite gem! :-)
Check it out:
https://github.com/fazibear/colorize
Installation:
gem install colorize
Usage:
require 'colorize'puts "I am now red".redputs "I am now blue".blueputs "Testing".yellow
Combining the answers above, you can implement something that works like the gem colorize without needing another dependency.
class String # colorization def colorize(color_code) "\e[#{color_code}m#{self}\e[0m" end def red colorize(31) end def green colorize(32) end def yellow colorize(33) end def blue colorize(34) end def pink colorize(35) end def light_blue colorize(36) endend
As String class methods (Unix only):
class Stringdef black; "\e[30m#{self}\e[0m" enddef red; "\e[31m#{self}\e[0m" enddef green; "\e[32m#{self}\e[0m" enddef brown; "\e[33m#{self}\e[0m" enddef blue; "\e[34m#{self}\e[0m" enddef magenta; "\e[35m#{self}\e[0m" enddef cyan; "\e[36m#{self}\e[0m" enddef gray; "\e[37m#{self}\e[0m" enddef bg_black; "\e[40m#{self}\e[0m" enddef bg_red; "\e[41m#{self}\e[0m" enddef bg_green; "\e[42m#{self}\e[0m" enddef bg_brown; "\e[43m#{self}\e[0m" enddef bg_blue; "\e[44m#{self}\e[0m" enddef bg_magenta; "\e[45m#{self}\e[0m" enddef bg_cyan; "\e[46m#{self}\e[0m" enddef bg_gray; "\e[47m#{self}\e[0m" enddef bold; "\e[1m#{self}\e[22m" enddef italic; "\e[3m#{self}\e[23m" enddef underline; "\e[4m#{self}\e[24m" enddef blink; "\e[5m#{self}\e[25m" enddef reverse_color; "\e[7m#{self}\e[27m" endend
And usage:
puts "I'm back green".bg_greenputs "I'm red and back cyan".red.bg_cyanputs "I'm bold and green and backround red".bold.green.bg_red
In my console:
Additionally,
def no_colors self.gsub /\e\[\d+m/, ""end
removes formatting characters.
Note
puts "\e[31m" # set format (red foreground)puts "\e[0m" # clear formatputs "green-#{"red".red}-green".green # will be green-red-normal, because of \e[0