Skip to content

Instantly share code, notes, and snippets.

@danielpowell4
Last active August 31, 2016 06:19
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 danielpowell4/0b6dfeb405d0dee0b010d88aed41c1b6 to your computer and use it in GitHub Desktop.
Save danielpowell4/0b6dfeb405d0dee0b010d88aed41c1b6 to your computer and use it in GitHub Desktop.
Converts RGB color values into equivalent hex codes in Ruby
# best solution
def rgb(r,g,b)
"%.2X%.2X%.2X" % [r,g,b].map{|c| [[c,255].min,0].max}
end
# needs a more DRY way of handling single digit hex conversion
def rgb(r, g, b)
[r,g,b].map{ |c| [[c,255].min,0].max > 16 ? [[c,255].min,0].max.to_s(16) : "0#{[[c,255].min,0].max.to_s(16)}"}.join.upcase
end
# needs a more clever way of handling upper and lower bounds
def rgb(r, g, b)
[r,g,b].map{ |c| c < 255 ? c : 255}.map{ |c| c > 0 ? c : 0}.map{ |c| c > 16 ? c.to_s(16) : "0#{c.to_s(16)}"}.join.upcase
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment