是否有一个针对Linux终端中字符串着色的Ruby模块?
我更喜欢 Rainbow gem,因为它也支持 Windows,如果已经安装了 win32console gem。
你可以像这样使用:
puts "some " + "red".color(:red) + " and " + "blue on yellow".color(:blue).background(:yellow)
只需要从"\e[##m"
开始,以"\e[0m"
结束即可。
将##替换为颜色编号。例如:
31:红色
32:绿色
33:黄色
34:蓝色
35:洋红色
36:青色
37:灰色
1:粗体(可与任何颜色一起使用)
这是一个Ruby脚本,用于显示所有终端颜色。 下载或运行以下代码。
def color(index)
normal = "\e[#{index}m#{index}\e[0m"
bold = "\e[#{index}m\e[1m#{index}\e[0m"
"#{normal} #{bold} "
end
8.times do|index|
line = color(index + 1)
line += color(index + 30)
line += color(index + 90)
line += color(index + 40)
line += color(index + 100)
puts line
end
class String
def black; "\033[30m#{self}\033[0m" end
def red; "\033[31m#{self}\033[0m" end
def green; "\033[32m#{self}\033[0m" end
def brown; "\033[33m#{self}\033[0m" end
def blue; "\033[34m#{self}\033[0m" end
def magenta; "\033[35m#{self}\033[0m" end
def cyan; "\033[36m#{self}\033[0m" end
def gray; "\033[37m#{self}\033[0m" end
end
用法和使用:
puts "This prints green".green
puts "This prints red".red
我是 Ruby colorize gem 的忠实粉丝,最近刚刚下载了它。一旦你将其下载并包含到你的程序中,你就可以添加
.colorize(:blue)
在任何字符串的末尾添加。您可以使用大多数颜色,包括在颜色之前加上light_,如下所示:
.colorize(:light_blue)
你也可以设置背景颜色,例如:
puts "mytext".colorize(:background => :green
彩色下划线, 例如:
puts "mytext".on_blue.underline
或者也可以使用类似HTML的标签
puts <blue> "text text text" </blue>
要为GitHub上的代码着色,请访问这个链接。
您可以通过输入以下命令来安装colorize gem:
gem install colorize
在你的终端、命令提示符或其他类似界面中输入此命令。然后将这段代码放入你的文件中,在你使用它之前。
例如:
require 'rubygems'
require 'colorize'
puts "mytext".colorize(:red)
但是不是:
puts "mytext".colorize(:red)
require 'rubygems'
require 'colorize'
在使用 gem 之前,必须将 require 语句放在程序的行中。
"string".red
可以获得红色文本。更多信息 :D - omninonsense