Skip to content

Instantly share code, notes, and snippets.

@mrrooijen
Forked from Jared-Prime/gist:2423065
Created October 21, 2012 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrrooijen/3926859 to your computer and use it in GitHub Desktop.
Save mrrooijen/3926859 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!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment