Reputation: 16193
I am new to Ruby and I want a part of a string to be colored. For this, I wrote a class Painter
class Painter
Red='\033[0;31m' # Red color
Green='\033[0;32m' # Green color
.
.
.
def paint(text, color)
return "#{color}#{text}\e[0m"
end
end
The way I use this is
puts "Green color looks like #{Painter.new.paint("this", Painter::Green)} and Red color looks like #{Painter.new.paint("this", Painter::Red)}"
I expect the output to look like this -
But the output on the console looks like -
I can solve the problem if I write methods like
def greenify(text)
return "\033[0;32m#{text}\e[0m"
end
But this means too many methods for one cause. Is there a way I can generify this?
Upvotes: 0
Views: 1085
Reputation: 401
If you want to use an existing solution for this, I recommend you take a look at the gem Colorize. You can not only colorize your string, but make them bold too. Example:
require 'colorize'
puts 'this is a blue string'.blue
puts "this is part #{'blue'.blue} and part #{'red'.red}"
puts "this is part #{'blue'.blue}, part #{'red'.red} and bold".bold
Upvotes: 2