Olly Legg home

RGB helper method

25 Mar 2009

Web Inspector in SafariI use Safari for my day to day development and while the ‘Inspect Element’ command has been much improved since earlier versions – I still can’t find out the foreground or background colours in hexadecimal notation.

The following ruby snippet converts from the format that Safari provides into hexadecimal. I find that its really useful to put in .irbrc so that its always available for quick conversions in IRB.

def rgb(*colours)
  colours.inject('#') do |code, colour| 
    code += colour.to_s(16).rjust(2, '0').upcase

I’m of the school of thought that every bit of code should be tested, mainly to preserve my sanity, so here are the specs for the following method.

describe "#rgb" do
  it "should convert rgb(0, 0, 0) to '#000000'" do
    rgb(0, 0, 0).should == '#000000'
  it "should convert rgb(190, 215, 205) to '#BED7CD'" do
    rgb(190, 215, 205).should == '#BED7CD'
  it "should convert rgb(255, 255, 255) to '#FFFFFF" do
    rgb(255, 255, 255).should == '#FFFFFF'