Skip to content

Instantly share code, notes, and snippets.

@scharfie
Last active June 1, 2022 13:18
Show Gist options
  • Save scharfie/38c7d27676b907ad9f16fb8afdbdaaca to your computer and use it in GitHub Desktop.
Save scharfie/38c7d27676b907ad9f16fb8afdbdaaca to your computer and use it in GitHub Desktop.
module StringRGB
def rgb(r, g=nil, b=nil)
original = r
if g.nil?
# check for 'short' form values like 0x8cf and expand to 0x88ccff
if r < 4096
b = r & 0xf | (r << 4 & 0xf0)
g = (r >> 4 & 0xf) | (r & 0xf0)
r = (r >> 8 & 0xf) | (r >> 4 & 0xf0)
else
b = r & 0xff
g = (r >> 8) & 255
r = (r >> 16) & 255
end
end
"\x1b[38;2;#{r};#{g};#{b}m#{self}\x1b[0m"
end
end
String.include StringRGB
# example
# puts "FAIL".rgb(0xf00) # short-hand for 0xff0000
# puts "PASS".rgb(0x00ff00)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment