Posted 23 days ago. Visible to the public.

Ruby: How to convert hex color codes to rgb or rgba

When you have a hex color code, you can easily convert it into its RGB values using plain Ruby.

Copy
>> "#ff8000".match(/^#(..)(..)(..)$/).captures.map(&:hex) => [255, 128, 0]

You can use that to implement a simple "hex to CSS rgba value with given opacity" method:

Copy
def hex_color_to_rgba(hex, opacity) rgb = hex.match(/^#(..)(..)(..)$/).captures.map(&:hex) "rgba(#{rgb.join(", ")}, #{opacity})" end
Copy
>> hex_color_to_rgba("#ff8000", 0.5) => "rgba(255, 128, 0, 0.5)"

If you need to support RGBA hex color codes, you need to handle a 4th hex pair. Example:

Copy
def hex_color_to_rgba(hex) *rgb, alpha = hex.match(/^#(..)(..)(..)(..)?$/).captures.map { |hex_pair| hex_pair&.hex } opacity = (alpha || 255) / 255.0 "rgba(#{rgb.join(", ")}, #{opacity.round(2)})" end
Copy
>> hex_color_to_rgba("#ff8000") => "rgba(255, 128, 0, 1)" >> hex_color_to_rgba("#ff8000aa") => "rgba(255, 128, 0, 0.67)"

If you also need to support 3-character hex color codes, it becomes ugly. Note that there is no short RGBA style like #f80a.

Copy
def hex_color_to_rgba(hex) if hex =~ /^#...$/ hex = hex.split(//).map { |single| single * 2 }.join[1..] end *rgb, alpha = hex.match(/^#(..)(..)(..)(..)?$/).captures.map { |hex_pair| hex_pair&.hex } opacity = (alpha || 255) / 255.0 "rgba(#{rgb.join(", ")}, #{opacity.round(2)})" end
Copy
>> hex_color_to_rgba("#f80") => "rgba(255, 136, 0, 1)" >> hex_color_to_rgba("#ff8800") => "rgba(255, 136, 0, 1)" >> hex_color_to_rgba("#ff8800aa") => "rgba(255, 136, 0, 0.67)"

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
19 days ago
by Tobias Kraze
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more