是否有像
Term::ANSIColor这样的宝石像256色彩终端一样工作?
my terminal的perl脚本
256colors2.pl非常出色,我想在我的ruby脚本中使用这些颜色,而不需要手动插入ANSI代码.
解决方法
这是256colors2.pl脚本对ruby的修改,并从
this guide提供了一些帮助.它定义了一个print_color(文本,前景,背景)方法,应该很容易适用于您的项目.它以彩色打印字符串,然后将颜色重置为终端默认值.如果您愿意,应该很容易跳过重置.
def rgb(red,green,blue) 16 + (red * 36) + (green * 6) + blue end def gray(g) 232 + g end def set_color(fg,bg) print "\x1b[38;5;#{fg}m" if fg print "\x1b[48;5;#{bg}m" if bg end def reset_color print "\x1b[0m" end def print_color(txt,fg,bg) set_color(fg,bg) print txt reset_color end # convenience method def rgb_cube for green in 0..5 do for red in 0..5 do for blue in 0..5 do yield [red,blue] end print " " end puts end end # rgb list on black bg rgb_cube do |red,blue| print_color("%d%d%d " % [red,blue],rgb(red,blue),nil) end puts # rgb list on white bg rgb_cube do |red,15) end puts # system palette: print "System colors:\n"; (0..7).each do |color| print_color(" ",nil,color) end puts (8..15).each do |color| print_color(" ",color) end puts puts # color cube print "Color cube,6x6x6:\n" rgb_cube do |red,blue| print_color(" ",blue)) end puts # grayscale ramp print "Grayscale ramp:\n" for g in (0..23) do print_color(" ",gray(g)) end puts puts