5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyの標準出力に僕も色をつけてみた

Posted at

『端末に出力する時に色を付けたいなぁ・・・。』と眺めていたら。。。
Ruby - 標準出力に色をつける - Qiita
『ほぉ?(☆▽☆)』と思ったので、やってみた

コード

term_color.rb
module TermColor
  COLORS = {black: 30, red: 31, green: 32, yellow: 33,  blue: 34, magenta: 35, syan: 36, white: 37, clear: nil}
  module ModuleMethods
    def method_missing(method, *args)
      if COLORS.has_key?(method)
        self.instance_eval <<-EOS
          def #{method}
            self.out_color_sequence(#{COLORS[method]})
          end
        EOS
        self.__send__(method)
      else
        super
      end
    end

    def out_color_sequence(num = nil)
      print "\e[#{num.to_s}m"
    end
  end

  extend ModuleMethods
end

if $0 == __FILE__
  TermColor.red
  puts "tomato"
  TermColor.black
  puts "coffee"
  TermColor.blue
  puts "blue hawaii"
  TermColor.blue
  puts "soda"
  TermColor.white
  puts "milk"
  TermColor.clear
end
  • 写経してもよかったのですが、ゴーストメソッドの学習がてらmethod_missingで遊んでみました。
  • 実行時に無ければメソッドを作って行くはずです。

実行結果

実行結果

  • 色が付きました!!!

・・・!!( ; ロ)゚ ゚

ところで、投稿前になって気づいたのですが・・・

まとめ

結局、gem辺りでインストールして、requireが良いようです!w
以上、ゴーストメソッドの作り方でした!(

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?