Rajkiran Rajkiran - 2 years ago 79
Ruby Question

Colorise part of string in Ruby

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"

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 -
expected output

But the output on the console looks like -
problematic output

I can solve the problem if I write methods like

def greenify(text)
return "\033[0;32m#{text}\e[0m"

But this means too many methods for one cause. Is there a way I can generify this?

Answer Source

It's because you use single quotes for the colors. Escape sequences like \033 are not handled in single quotes but are in double quotes.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download