Pregunta

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.

¿Fue útil?

Solución

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top