Skip to content

Instantly share code, notes, and snippets.

@idlehands
Created October 22, 2012 21:17
Show Gist options
  • Save idlehands/3934434 to your computer and use it in GitHub Desktop.
Save idlehands/3934434 to your computer and use it in GitHub Desktop.
color using ANSI escape codes

I have the bad habit of always using puts when I probably use print. As a a result, I was having trouble with the gems that were usable for colorizing my ToDo 3.0. I figured out a gem-free solution, using ANSI escape codes, and thought I'd share.

WARNING: don't be surprised if someone comes along and tells you this is the worst thing you could ever do. I have NO idea if it is a kosher solution, but it worked and it required VERY little change to my code. Additionally, this method works on the systems we have at DBC (and on mine) but I don't know if it is universal (I "think" it is).

A little set-up: I decided that I wanted to handle the color coding of priorities(and the keeping of the priorities) in my Todo class and not my TodoList class. Each todo keeps track of its own priority level, so I just modified the to_s method to include the color.

ANSI escape codes are used to send things to the output that aren't printed, not unlike the \ before the n of a new line. I'll show my code and then explain what it's doing and how I go there:

`` def colors {1 => "\e[31m", 2 => "\e[33m", 3 => "\e[32m", 4 => "\e[34m"} # 1.red 2.yellow 3.green 4.blue end

def to_s colors[priority] + "priority: #{priority} #{name}: #{complete_in_english}, tags: #{tags.map { |tag| tag }.join(" ")}" + "\e[0m" end

``

I found list of colors : http://bluesock.org/~willg/dev/ansi.html#sequences and played around until I realized that I could lead a string with a separate string containing just the escape code and the color I wanted. I hashed the escape codes to automate the color assignment for each Todo. After giving the string, the \e[0, is the escape code to set the text back to the default color. I made the hash for the colors a separate method to give future iterations of the program flexibility to re-use those colors, but it could have just as easily been a hash inside of the to_s method.

Let me know if you have any questions or ideas. I, admittedly, don't know much about all of this, but the few people who saw it seemed interested in knowing more.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment