2017-07-27 36 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