想我會添加其他的解決方案,因爲它做的事情有點不同,包括多個顏色代碼:
首先一些例子...
使用方法鏈接:
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