Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminal color in Ruby

Is there a Ruby module for colorizing strings in a Linux terminal?

like image 390
gustavgans Avatar asked Jul 10 '09 10:07

gustavgans


4 Answers

I prefer the Rainbow gem since it also supports Windows if the win32console gem has been installed.

You can use it like this:

puts "some " + "red".color(:red) + " and " + "blue on yellow".color(:blue).background(:yellow)
like image 81
Andy Avatar answered Oct 07 '22 02:10

Andy


Ehm, OK, Google was my friend :)

http://term-ansicolor.rubyforge.org/

like image 26
gustavgans Avatar answered Oct 07 '22 01:10

gustavgans


All you have to do is start with "\e[##m" and end with "\e[0m"

Just replace the ## with the color number. Examples are:

  • 31:Red
  • 32:Green
  • 33:Yellow
  • 34:Blue
  • 35:Magenta
  • 36:Teal
  • 37:Grey

1:Bold (can be used with any color)

Here is a Ruby script to show all the terminal colors. Download it or run the code below.

def color(index)
  normal = "\e[#{index}m#{index}\e[0m"
  bold = "\e[#{index}m\e[1m#{index}\e[0m"
  "#{normal}  #{bold}  "
end

8.times do|index|
  line = color(index + 1)
  line += color(index + 30)
  line += color(index + 90)
  line += color(index + 40)
  line += color(index + 100)
  puts line
end
like image 32
mvndaai Avatar answered Oct 07 '22 03:10

mvndaai


Using String class methods like:

class String
def black;          "\033[30m#{self}\033[0m" end
def red;            "\033[31m#{self}\033[0m" end
def green;          "\033[32m#{self}\033[0m" end
def brown;          "\033[33m#{self}\033[0m" end
def blue;           "\033[34m#{self}\033[0m" end
def magenta;        "\033[35m#{self}\033[0m" end
def cyan;           "\033[36m#{self}\033[0m" end
def gray;           "\033[37m#{self}\033[0m" end
end

and usage:

puts "This prints green".green
puts "This prints red".red
like image 44
TantrajJa Avatar answered Oct 07 '22 01:10

TantrajJa