Dinos_12345 Dinos_12345 - 2 years ago 115
Ruby Question

Color codes and string interpolation

I am trying to colorize text. Say I want blue text. This is the way I get it:

"\e[34mThis is blue text.\e[0m"

I am using
to create multiple methods (one for each color). I keep the color code for each color in an array. I iterate over both the color array and the color code, and do this:


When I run it, I get
instead of the colorized text.

Any thoughts? If, instead of
, I put the actual code, it works, but that'd be like 20
s, one for each color, and it won't be DRY.

Answer Source

You are likely a victim of copy-paste :)

#               ⇓  incorrect
puts "\e#{code}m[#{self}\e[0m"

#       ⇓  correct
puts "\e[#{code}m#{self}\e[0m"

The opening square bracket should follow \e, not m.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download