Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
256-color hex intepretation for terminal colorization
#!/usr/bin/env ruby
# frozen_string_literal: true
# 256-color hex interpretation for terminal colorization
#
# Usage
# "text".color256(foreground, background)
#
# print "Colorize this".color256('#f7921e', '#666')
# String category
module Color256
def fg(fgc)
"\x1b[38;2;#{fgc.rgb}m"
end
def bg(bgc)
"\x1b[48;2;#{bgc.rgb}m"
end
def reset
"\x1b[0m"
end
def rgb
hex_string = sub(/^#?/, '')
hex_string = hex_string.split(//).map { |a| a * 2 }.join('') if hex_string =~ /^#?[a-f0-9]{3}$/i
parts = hex_string.match(/#?(?<r>..)(?<g>..)(?<b>..)/)
t = []
%w[r g b].each do |e|
t << parts[e].hex
end
t.join(';')
end
def color256(fgc, bgc = nil)
out = ''
out += fg(fgc)
out += bg(bgc) if bgc
out += self
out + reset
end
end
class ::String
include Color256
end
def test
256.times do |r|
256.times do |g|
256.times do |b|
c = ''
[r, g, b].each { |comp| c += format('%02x', comp) }
print ' '.color256('000', c)
end
end
end
end
if __FILE__ == $0
print ARGV[0].color256(ARGV[1], ARGV[2])
end
@bobbykjack
Copy link

bobbykjack commented May 31, 2022

I think there's a bug here. If you call:

rgb('#abc')

you'll get bad values because line 28 will duplicate the hash as well as the individual color components, then each character will be shifted by 1 on line 30.

@ttscoff
Copy link
Author

ttscoff commented May 31, 2022

Ah, yeah, that needs to strip the octothorp.

@ttscoff
Copy link
Author

ttscoff commented May 31, 2022

Should be fixed now.

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