Created
April 19, 2012 18:57
-
-
Save Jared-Prime/2423065 to your computer and use it in GitHub Desktop.
Converting RGB to HEX in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can use
String#rjust
to pad, so L40-47 could beblue.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. 🎉