Skip to content

Instantly share code, notes, and snippets.

@krupenik
Forked from neves/red-green.png
Last active October 23, 2015 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krupenik/0f0bab9d5960d2cf776e to your computer and use it in GitHub Desktop.
Save krupenik/0f0bab9d5960d2cf776e to your computer and use it in GitHub Desktop.
# Ruby has great gems for coloring print to terminal,
# but sometimes you just need to print a couple of times and
# don't want to add another gem just for that.
# For example, instead of:
puts "\e[31mThis is red!\e[0m"
puts "\e[32mThis is green!\e[0m"
# reopen the String class and add all the colors you need:
class String
def red
"\e[31m#{self}\e[0m"
end
def green
"\e[32m#{self}\e[0m"
end
end
# and then use them!
puts "Red again!".red
puts "Green again!".green
puts "Mixed %s with %s!" % ["red".red, "green".green]
# Other example:
a = 2
b = 3
format = "%s + %s = %s"
puts format % [a.to_s.red, b.to_s.red, (a + b).to_s.green]
# instead of the unreadable code:
puts "\e[31m#{a}\e[0m + \e[31m#{b}\e[0m = \e[32m#{sum}\e[0m"
@neves
Copy link

neves commented Oct 23, 2015

I updated my code with alternative solutions based on yours.
https://gist.github.com/neves/f9602ddd8653d03167f2

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