想我会添加其他的解决方案,因为它做的事情有点不同,包括多个颜色代码:
首先一些例子...
使用方法链接:
String.include(AnsiTextStyles)
puts "How are you?".blue.bold + " " + 'I am good!'.red.bold
puts '%s %s' % ["How are you?".blue.bold, 'I am good!'.red.bold]
使用style
方法和应用的多个属性:
puts "How are you?".style(:red)
puts 'I am good!'.style(:blue, :underline)
puts 'Good to hear'.style([:bg_magenta, :blink])
这可被用来存储风格以某种方式属性以后应用:
text_styles = {
red_bold: [:red, :bold],
blue_underline: [:blue, :underline],
pretty: [:bg_magenta, :blink],
}
text_styles.each do |name, style|
styled_text = "Text styled multiple ways".style(style)
puts "%s: %s" % [name, styled_text]
end
我在this gist I created和ex上给了几个例子将代码放大以包含优化,以便修改字符串的范围。
这是基本的代码:
module AnsiTextStyles
TEXT_ATTRIBUTES = {
# text properties
none: 0, # turn off all attributes
bold: 1, bright: 1, # these do the same thing really
italic: 3, underline: 4, blink: 5,
reverse: 7, # swap foreground and background colours
hide: 8, # foreground color same as background
# foreground colours
black: 30, grey: 90, lt_grey: 37, :white => 97,
red: 31, lt_red: 91,
green: 32, lt_green: 92,
dk_yellow: 33, brown: 33, yellow: 93,
blue: 34, lt_blue: 94,
magenta: 35, pink: 95, lt_magenta: 95,
cyan: 36, lt_cyan: 96,
default: 39,
# background colours
bg_black: 40, bg_grey: 100, bg_lt_grey: 47, bg_white: 107,
bg_red: 41, bg_lt_red: 101,
bg_green: 42, bg_lt_green: 102,
bg_dk_yellow: 43, bg_brown: 43, bg_yellow: 103,
bg_blue: 44, bg_lt_blue: 104,
bg_magenta: 45, bg_pink: 105, bg_lt_magenta: 105,
bg_cyan: 46, bg_lt_cyan: 106,
}
def self.text_attributes
TEXT_ATTRIBUTES.keys
end
# applies the text attributes to the current string
def style(*text_attributes)
codes = TEXT_ATTRIBUTES.values_at(*text_attributes.flatten).compact
"\e[%sm%s\e[m" % [codes.join(';'), self.to_s]
end
end
我在想红宝石命令行的文本,当我问我的问题早在2010年的问题有超过11000的意见和外部链接的堆栈。当我形成我的问题时,我不会想到要寻找“彩色的ruby输出”,事实上在搜索时找不到答案。暗示的答案可能是相似的,但问题提出的方式完全不同。我看到两个问题都是不同的,但很高兴能让他们联系起来。 – Evolve 2014-03-03 05:42:52