Skip to content

Instantly share code, notes, and snippets.

@syusui-s
Last active December 15, 2015 20:41
Show Gist options
  • Save syusui-s/5320371 to your computer and use it in GitHub Desktop.
Save syusui-s/5320371 to your computer and use it in GitHub Desktop.
[Ruby]putsする文字列に色を付けるやつ。シェルで、echo -e しても動いた。coloringの引数には、1つ目に文字列、2つ目以降に装飾・文字色・背景色(複数指定可)をString型で、カンマ区切りで指定する。ライセンスはMIT License
Copyright (c) 2013 Shusui MOYATANI
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
module Coloring
COLORS = {
'bold' => '1',
'underscore'=> '4',
'black' => '30',
'red' => '31',
'green' => '32',
'yellow' => '33',
'blue' => '34',
'magenta' => '35',
'cyan' => '36',
'white' => '37',
'bg_black' => '40',
'bg_red' => '41',
'bg_green' => '42',
'bg_yellow' => '43',
'bg_blue' => '44',
'bg_magenta'=> '45',
'bg_cyan' => '46',
'bg_white' => '47'
}.freeze
def coloring(text, *a_colors)
"\e[" + a_colors.map!{|s| COLORS.key?(s) ? COLORS[s] : s }.join(";") + "m#{text}\e[0m" end
module_function :coloring
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment