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.

有帮助吗?

解决方案

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top