Skip to content

Instantly share code, notes, and snippets.

@amirrajan
Created February 29, 2020 21:56
Show Gist options
  • Save amirrajan/46cafad5f024916264f1c8c0c16de390 to your computer and use it in GitHub Desktop.
Save amirrajan/46cafad5f024916264f1c8c0c16de390 to your computer and use it in GitHub Desktop.
Ruby function to convert hex to RGB without using regex.
class String
def color
if self.length != 6 && self.length != 8
raise "Color must be in the format rrggbb or rrggbbaa. This is what you provided #{self}."
end
if self.length == 6
working_number = 0xff000000 + self.to_i(16)
else
working_number = [*self[-2..-1], *self[0..5]].join.to_i(16)
end
components = working_number.to_s(16).each_char.each_slice(2).map do |parts|
parts.join.to_i(16)
end
[components[1..-1], components[0]]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment