abachrome
How do I parse a hex color string in Ruby?
Abachrome parses hex color strings with Abachrome.from_hex, accepting #RGB, #RRGGBB, and the bare forms without the # prefix.
require 'abachrome'
red = Abachrome.from_hex('#ff0000')
green = Abachrome.from_hex('#0f0') # shorthand
blue = Abachrome.from_hex('0000ff') # no leading #
puts red.rgb_hex # => "ff0000"
puts green.rgb_hex # => "00ff00"
Reading the Components
Once parsed, the color lives in sRGB space and exposes its channels as floating-point values in the 0.0–1.0 range:
color = Abachrome.from_hex('#3a86ff')
puts color.coordinates[0] # red => ~0.227
puts color.coordinates[1] # green => ~0.525
puts color.coordinates[2] # blue => 1.0
Round-Tripping to CSS
Use Abachrome::Outputs::CSS.format to emit a CSS-safe hex string, or format_rgb for an rgb() function value:
color = Abachrome.from_hex('#3a86ff')
Abachrome::Outputs::CSS.format(color) # => "#3a86ff"
Abachrome::Outputs::CSS.format_rgb(color) # => "rgb(58, 134, 255)"
Notes
- Hex parsing is case-insensitive (
#FF0000and#ff0000are equivalent). - Alpha channels are not expressed in hex strings; use
Abachrome.from_rgbwith a fourth argument if you need transparency.