abachrome

How do I convert a hex color to RGB values in Ruby?

Parse the hex string with Abachrome.from_hex, then read the sRGB coordinates. Abachrome stores channel values as floats in the 0.0–1.0 range; multiply by 255 to get the 0–255 integers most libraries and APIs expect.

Float (0.0–1.0) Channels

require 'abachrome'

color = Abachrome.from_hex('#3a86ff')
r, g, b = color.coordinates

puts r  # => 0.22745...
puts g  # => 0.52549...
puts b  # => 1.0

Integer (0–255) Channels

color = Abachrome.from_hex('#3a86ff')
r, g, b = color.coordinates.map { |c| (c * 255).round }

puts "rgb(#{r}, #{g}, #{b})"  # => "rgb(58, 134, 255)"

Hex → CSS rgb() String

Abachrome::Outputs::CSS.format_rgb does this in one call:

color = Abachrome.from_hex('#06d6a0')
puts Abachrome::Outputs::CSS.format_rgb(color)  # => "rgb(6, 214, 160)"

Including the Alpha Channel

color = Abachrome.from_hex('#3a86ff')
r, g, b = color.coordinates.map { |c| (c * 255).round }
a = color.alpha  # => 1.0

puts "rgba(#{r}, #{g}, #{b}, #{a})"  # => "rgba(58, 134, 255, 1.0)"

Batch Conversion

hex_values = %w[#ff6b6b #ffd93d #6bcb77 #4d96ff]

hex_values.each do |hex|
  color   = Abachrome.from_hex(hex)
  r, g, b = color.coordinates.map { |c| (c * 255).round }
  puts "#{hex} => rgb(#{r}, #{g}, #{b})"
end

Notes

  • For the reverse operation (RGB integers → hex), use Abachrome.from_rgb(r/255.0, g/255.0, b/255.0) followed by color.rgb_hex.
  • Abachrome uses BigDecimal internally; the floats you see from coordinates are already rounded for display.