2017-07-27 34 views
0

我是Ruby的新手,我想要一部分字符串被着色。对于这一点,我写了一个类画家Colorise在Ruby中的部分字符串

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 

我用这

puts "Green color looks like #{Painter.new.paint("this", Painter::Green)} and Red color looks like #{Painter.new.paint("this", Painter::Red)}" 

我希望输出看起来像这样的方式 - expected output

但在控制台看起来输出像 - problematic output

我可以解决这个问题,如果我写的方法,如

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

但是这意味着一个原因的方法太多。有没有一种方法可以使这种情况变得生动?

+1

这是因为您使用单引号的颜色。像'\ 033'这样的转义序列不是用单引号处理,而是用双引号https://stackoverflow.com/a/16601500/3072566 – litelite

+0

哦谢谢,你可以添加这个作为答案,以便它可以帮助别人。它完美的作品。 – Rajkiran

回答

0

这是因为您使用单引号的颜色。像\033这样的转义序列不是用单引号处理,而是用双引号。

Source

2

如果你想使用这个现有的解决方案,我建议你看看宝石Colorize。你不仅可以给你的字符串着色,还可以让它们变得粗体。例如:

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 
+0

这是个很棒的事情。谢谢。 – Rajkiran