292

Ruby を使用して、端末で出力するために背景と前景のテキストの色付けを実行するにはどうすればよいですか?

Pascal をプログラミングするときtextcolor(…)、小さな教育プログラムをより見栄えよく見せるために独自の手順を作成していたことを覚えています。

それと同等のものをRubyでコーディングするにはどうすればよいでしょうか? これに役立つコア ライブラリの組み込みサポートはありますか? そうでない場合、それを追加する慣用的な方法は何ですか?

4

11 に答える 11

409

Colorize is my favorite gem! :-)

Check it out:

https://github.com/fazibear/colorize

Installation:

gem install colorize

Usage:

require 'colorize'

puts "I am now red".red
puts "I am now blue".blue
puts "Testing".yellow
于 2009-09-28T20:38:16.107 に答える
271

上記の回答を組み合わせることで、別の依存関係を必要とせずに、gem colorize のように機能するものを実装できます。

class String
  # colorization
  def colorize(color_code)
    "\e[#{color_code}m#{self}\e[0m"
  end

  def red
    colorize(31)
  end

  def green
    colorize(32)
  end

  def yellow
    colorize(33)
  end

  def blue
    colorize(34)
  end

  def pink
    colorize(35)
  end

  def light_blue
    colorize(36)
  end
end
于 2012-07-14T09:02:56.720 に答える
247

String クラスのメソッドとして (Unix のみ):

class String
def black;          "\e[30m#{self}\e[0m" end
def red;            "\e[31m#{self}\e[0m" end
def green;          "\e[32m#{self}\e[0m" end
def brown;          "\e[33m#{self}\e[0m" end
def blue;           "\e[34m#{self}\e[0m" end
def magenta;        "\e[35m#{self}\e[0m" end
def cyan;           "\e[36m#{self}\e[0m" end
def gray;           "\e[37m#{self}\e[0m" end

def bg_black;       "\e[40m#{self}\e[0m" end
def bg_red;         "\e[41m#{self}\e[0m" end
def bg_green;       "\e[42m#{self}\e[0m" end
def bg_brown;       "\e[43m#{self}\e[0m" end
def bg_blue;        "\e[44m#{self}\e[0m" end
def bg_magenta;     "\e[45m#{self}\e[0m" end
def bg_cyan;        "\e[46m#{self}\e[0m" end
def bg_gray;        "\e[47m#{self}\e[0m" end

def bold;           "\e[1m#{self}\e[22m" end
def italic;         "\e[3m#{self}\e[23m" end
def underline;      "\e[4m#{self}\e[24m" end
def blink;          "\e[5m#{self}\e[25m" end
def reverse_color;  "\e[7m#{self}\e[27m" end
end

そして使用法:

puts "I'm back green".bg_green
puts "I'm red and back cyan".red.bg_cyan
puts "I'm bold and green and backround red".bold.green.bg_red

私のコンソールで:

ここに画像の説明を入力してください

さらに、

def no_colors
  self.gsub /\e\[\d+m/, ""
end

フォーマット文字を削除します。

ノート

puts "\e[31m" # set format (red foreground)
puts "\e[0m"   # clear format
puts "green-#{"red".red}-green".green # will be green-red-normal, because of \e[0
于 2013-05-03T16:03:19.907 に答える
43

Erik Skoglund などの回答に基づいて、基本的なカラー モードをテストするための簡単な方法を書きました。

#outputs color table to console, regular and bold modes
def colortable
  names = %w(black red green yellow blue pink cyan white default)
  fgcodes = (30..39).to_a - [38]

  s = ''
  reg  = "\e[%d;%dm%s\e[0m"
  bold = "\e[1;%d;%dm%s\e[0m"
  puts '                       color table with these background codes:'
  puts '          40       41       42       43       44       45       46       47       49'
  names.zip(fgcodes).each {|name,fg|
    s = "#{fg}"
    puts "%7s "%name + "#{reg}  #{bold}   "*9 % [fg,40,s,fg,40,s,  fg,41,s,fg,41,s,  fg,42,s,fg,42,s,  fg,43,s,fg,43,s,  
      fg,44,s,fg,44,s,  fg,45,s,fg,45,s,  fg,46,s,fg,46,s,  fg,47,s,fg,47,s,  fg,49,s,fg,49,s ]
  }
end

出力例: ルビーカラーテスト

于 2013-08-16T18:46:16.467 に答える
39

ANSI エスケープ シーケンスを使用して、コンソールでこれを行うことができます。これが Linux と Mac OS X で動作することはわかっていますが、Windows コンソール (cmd) が ANSI をサポートしているかどうかはわかりません。

私はJavaでそれをしましたが、アイデアは同じです。

// Foreground color
public static final String BLACK_TEXT()   { return "\033[30m";}
public static final String RED_TEXT()     { return "\033[31m";}
public static final String GREEN_TEXT()   { return "\033[32m";}
public static final String BROWN_TEXT()   { return "\033[33m";}
public static final String BLUE_TEXT()    { return "\033[34m";}
public static final String MAGENTA_TEXT() { return "\033[35m";}
public static final String CYAN_TEXT()    { return "\033[36m";}
public static final String GRAY_TEXT()    { return "\033[37m";}

// Background color
public static final String BLACK_BACK()   { return "\033[40m";}
public static final String RED_BACK()     { return "\033[41m";}
public static final String GREEN_BACK()   { return "\033[42m";}
public static final String BROWN_BACK()   { return "\033[43m";}
public static final String BLUE_BACK()    { return "\033[44m";}
public static final String MAGENTA_BACK() { return "\033[45m";}
public static final String CYAN_BACK()    { return "\033[46m";}
public static final String WHITE_BACK()   { return "\033[47m";}

// ANSI control characters
public static final String RESET_COLORS() { return "\033[0m";}
public static final String BOLD_ON()      { return "\033[1m";}
public static final String BLINK_ON()     { return "\033[5m";}
public static final String REVERSE_ON()   { return "\033[7m";}
public static final String BOLD_OFF()     { return "\033[22m";}
public static final String BLINK_OFF()    { return "\033[25m";}
public static final String REVERSE_OFF()  { return "\033[27m";}
于 2009-09-28T20:35:18.983 に答える
19

他の答えはほとんどの人にとってうまくいきますが、これを行う「正しい」Unixの方法について言及する必要があります。すべてのタイプのテキスト端末がこれらのシーケンスをサポートしているわけではないため、さまざまなテキスト端末の機能を抽象化したterminfoデータベースに問い合わせることができます。これは主に歴史的な関心事のように思えるかもしれません – 現在使用されているソフトウェア端末は一般に ANSI シーケンスをサポートしています – しかし、(少なくとも) 1 つの実際的な効果があります: 環境変数TERMをに設定してdumb、そのようなスタイリングをすべて回避できると便利な場合があります。たとえば、出力をテキスト ファイルに保存する場合などです。また、物事を正しく行うのは気持ちがいいです。:-)

ruby-terminfo gemを使用できます。インストールするには C コンパイルが必要です。次のコマンドを使用して、Ubuntu 14.10 システムにインストールできました。

$ sudo apt-get install libncurses5-dev
$ gem install ruby-terminfo --user-install

次に、次のようにデータベースにクエリを実行できます (使用可能なコードのリストについては、 terminfo のマニュアル ページを参照してください)。

require 'terminfo' 
TermInfo.control("bold")
puts "Bold text"
TermInfo.control("sgr0")
puts "Back to normal."
puts "And now some " + TermInfo.control_string("setaf", 1) + 
     "red" + TermInfo.control_string("sgr0") + " text."

これは、物事をもう少し簡単に使用できるようにするためにまとめた小さなラッパークラスです。

require 'terminfo'

class Style
  def self.style() 
    @@singleton ||= Style.new
  end

  colors = %w{black red green yellow blue magenta cyan white}
  colors.each_with_index do |color, index|
    define_method(color) { get("setaf", index) }
    define_method("bg_" + color) { get("setab", index) }
  end

  def bold()  get("bold")  end
  def under() get("smul")  end
  def dim()   get("dim")   end
  def clear() get("sgr0")  end

  def get(*args)
    begin
      TermInfo.control_string(*args)
    rescue TermInfo::TermInfoError
      ""
    end
  end
end

使用法:

c = Style.style
C = c.clear
puts "#{c.red}Warning:#{C} this is #{c.bold}way#{C} #{c.bg_red}too much #{c.cyan + c.under}styling#{C}!"
puts "#{c.dim}(Don't you think?)#{C}"

上記の Ruby スクリプトの出力

(編集) 最後に、gem を必要としない場合は、ここで説明されているようtputに、プログラムに頼ることができます– Ruby の例:

puts "Hi! " + `tput setaf 1` + "This is red!" + `tput sgr0`
于 2015-03-22T21:30:25.250 に答える
13

宝石を必要とせずに動作させるために私がしたことは次のとおりです。

def red(mytext) ; "\e[31m#{mytext}\e[0m" ; end
puts red("hello world")

次に、引用符内のテキストのみが色付けされ、定期的にスケジュールされているプログラムに戻ります。

于 2013-01-29T20:58:41.313 に答える
12

I found a few:

http://github.com/ssoroka/ansi/tree/master

Examples:

puts ANSI.color(:red) { "hello there" }
puts ANSI.color(:green) + "Everything is green now" + ANSI.no_color

http://flori.github.com/term-ansicolor/

Examples:

print red, bold, "red bold", reset, "\n"
print red(bold("red bold")), "\n"
print red { bold { "red bold" } }, "\n"

http://github.com/sickill/rainbow

Example:

puts "this is red".foreground(:red) + " and " + "this on yellow bg".background(:yellow) + " and " + "even bright underlined!".underline.bright

If you are on Windows you may need to do a "gem install win32console" to enable support for colors.

Also the article Colorizing console Ruby-script output is useful if you need to create your own gem. It explains how to add ANSI coloring to strings. You can use this knowledge to wrap it in some class that extends string or something.

于 2009-09-28T20:38:34.203 に答える
8

これはあなたを助けるかもしれません: 色付きのルビー出力

于 2009-09-28T20:29:50.493 に答える
5

以前の回答が役立つことがわかりました。ただし、サードパーティのライブラリを使用せずにログ出力のようなものを色付けしたい場合、それらは法案に適合しませんでした. 以下は私のために問題を解決しました:

red = 31
green = 32
blue = 34

def color (color=blue)
  printf "\033[#{color}m";
  yield
  printf "\033[0m"
end

color { puts "this is blue" }
color(red) { logger.info "and this is red" }
于 2014-03-13T10:31:11.533 に答える