문제

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