Skip to content

Instantly share code, notes, and snippets.

@Jared-Prime
Created April 19, 2012 18:57
Show Gist options
  • Save Jared-Prime/2423065 to your computer and use it in GitHub Desktop.
Save Jared-Prime/2423065 to your computer and use it in GitHub Desktop.
Converting RGB to HEX in Ruby
# Beginning Rubyists: simply run >> ruby hex-convertions.rb to see examples
# or use irb to build the code on the fly
# you can convert HEX to DEC using the method .to_i(base),
# which converts a string to a decimal number from the specified base number
puts "00".to_i(16)
puts "FF".to_i(16)
# to get from DEC to HEX, simply use the method .to_s
puts 255.to_s(16)
puts 0.to_s(16)
# easy! Now let's split a standard CSS color into it Red Green and Blue components
white = "FFFFFF"
components = white.scan(/.{2}/)
puts components
# great, now try converting each component into DEC
components.each {|component| puts component.to_i(16)}
# given an RGB color, convert to HEX
@red_as_hex = ""
red = [255,0,0] # I'm cutting corners here; we also need to convert the CSS string rgb(255,0,0) to the array used on the left. It's easy.
red.each {|component| @red_as_hex << component.to_s(16) }
puts @red_as_hex
# notice a slight problem in the output... we got ff00 for the HEX "red".
# We need some way to print ff0000 to get the proper CSS value
# try a simple loop for now...
@blue_as_hex = ""
blue = [0,0,255]
blue.each do |component|
hex = component.to_s(16)
if component < 10
@blue_as_hex << "0#{hex}"
else
@blue_as_hex << hex
end
end
puts @blue_as_hex
# Now we've got all the tricks we need to shuffle between RGB and HEX.
# Next, we can start doing additive color theory!
@statico
Copy link

statico commented Sep 7, 2017

You can use String#rjust to pad, so L40-47 could be blue.each {|c| c.to_s(16).rjust(2, '0')}

Also, if you found this nice gist, you might want to check out the Chroma gem. It does color parsing and manipulation and everything. 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment