0

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 - 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"
end

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

Rajkiran
  • 15,845
  • 24
  • 74
  • 114
  • 1
    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 https://stackoverflow.com/a/16601500/3072566 – litelite Jul 27 '17 at 13:59
  • Ohh thanks, you can add this as an answer so that it'll help others. It works perfectly. – Rajkiran Jul 27 '17 at 14:02

2 Answers2

2

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
rodsoars
  • 401
  • 8
  • 16
0

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.

Source

litelite
  • 2,857
  • 4
  • 23
  • 33