【问题标题】:Terminal color in RubyRuby 中的终端颜色
【发布时间】:2010-11-09 16:12:00
【问题描述】:

是否有用于在 Linux 终端中为字符串着色的 Ruby 模块?

【问题讨论】:

  • 我不会发布答案,所以我不会恢复这个,但是有一个漂亮的宝石叫做“有色”。很简单:"string".red 获取红色文本。 More info:D
  • 您可以检查这一点,也有一些选项可以在不安装另一个 Gem 的情况下执行此操作:Colorized Ruby output

标签: 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)
      

      【讨论】:

      • 这是一个很棒的宝石。维护良好且简单。
      【解决方案4】:

      嗯,好吧,Google 是我的朋友 :)

      http://term-ansicolor.rubyforge.org/

      【讨论】:

      • 链接已损坏(超时)。
      【解决方案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
      

      【讨论】:

      • 准确简洁,最佳答案。
      猜你喜欢
      • 2014-07-04
      • 2018-09-30
      • 1970-01-01
      • 2010-11-27
      • 2017-06-25
      • 1970-01-01
      • 1970-01-01
      • 2015-11-19
      • 1970-01-01
      相关资源
      最近更新 更多