【问题标题】:Terminal color in RubyRuby 中的终端颜色
【发布时间】:2010-11-09 16:12:00
【问题描述】:
是否有用于在 Linux 终端中为字符串着色的 Ruby 模块?
【问题讨论】:
标签:
ruby
bash
shell
colors
terminal
【解决方案1】:
我是我最近下载的 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,请转到 The colorize GitHub。
您可以通过键入来安装 colorize gem
gem install colorize
进入您的终端、命令提示符等。然后把它放到你的文件中在你使用它之前。
例如:
require 'rubygems'
require 'colorize'
puts "mytext".colorize(:red)
但不是:
puts "mytext".colorize(:red)
require 'rubygems'
require 'colorize'
require 语句必须在你使用 gem 之前的行中。
【解决方案2】:
您所要做的就是以"\e[##m" 开头并以"\e[0m" 结尾
只需将## 替换为颜色编号即可。例如:
31:Red
32:Green
33:Yellow
34:Blue
35:Magenta
36:Teal
37:Grey
1:Bold (can be used with any color)
这是一个显示所有终端颜色的 Ruby 脚本。 Download it 或运行以下代码。
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
【解决方案3】:
我更喜欢Rainbow gem,因为如果安装了 win32console gem,它也支持 Windows。
你可以这样使用它:
puts "some " + "red".color(:red) + " and " + "blue on yellow".color(:blue).background(:yellow)
【解决方案5】:
使用 String 类方法,例如:
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