Rajkiran
Rajkiran

Reputation: 16193

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

Upvotes: 0

Views: 1085

Answers (2)

rodsoars
rodsoars

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

litelite
litelite

Reputation: 2851

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

Upvotes: 0

Related Questions