2

How to make color for a string in Ruby? For example, define a method make_color,

def make_color(str, :red) end 

Then the output will return the String str with red color.

I wonder whether there is a lib in ruby can help me do that?

ps: I prefer not using gem package.

2
  • Is this in the terminal? Commented Feb 20, 2014 at 4:11
  • @Linuxios, Yes, I will output the string in a UNIX/LINUX box terminal. Commented Feb 20, 2014 at 4:12

1 Answer 1

4

Take a look at colorize gem

Install the gem and you can use colorize method to specify the color you want

require 'colorize' puts "This is blue".colorize( :blue ) 

Or you can simply use the codes as you would in bash

for eg:

def make_color(str, color) colors = {:red => 31, :green => 32, :blue => 34} puts "\e[#{colors[color]}m #{str}\e[0m" end 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Vimsha, but what if we don't use gem?
nice job! That's my need.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.