Generating Random Hex Codes in Ruby

Posted Tue, 23 Jan 2007

Part of my new comment system for Blosxonomy includes an email verification system that requests the user to confirm their email before their comments will be displayed on the blog. To do this, I wrote a simple random-hex-code generator to build unique url's. When a comment is posted by a user with an unconfirmed email address, a random URL is generated using the random hex code, and emailed to that user.

Generating such codes in ruby is very simple, and often useful, so I thought I'd post the method I wrote to do it:

def generateUniqueHexCode( codeLength )
    validChars = ("A".."F").to_a + ("0".."9").to_a
    length = validChars.size

    hexCode = ""
    1.upto(codeLength) { |i| hexCode << validChars[rand(length-1)] }

    hexCode
end

validChars is initialized to be an array containing characters 'A' through 'F', and '0' through '9'. I then append codeLength random characters from that array to the hexCode string and return it.

While a more robust implementation would validate uniqueness against the list of already generated IDs, the assumption is that these ID's are short lived, and the likelihood of generating repeats IDs given a sufficient length (I use 64) is miniscule.

Related Books

The Ruby Programming Language C Programming Language (2nd Edition) (Prentice Hall Software) The 2007-2012 World Outlook for Fillister, Flat, Hex, Oval, Pan, Truss, and Other Tapping Screws and Flat, Oval, and Round Wood Screws Excluding Aircraft Types Programming Ruby: The Pragmatic Programmers' Guide, Second Edition Cocoa(R) Programming for Mac(R) OS X (3rd Edition)

Post a Comment




About

My name is Tim Fanelli, I am a software engineer in Northern NY. I spend most of my time working, and when I can, I try to post interesting things here.

Cigar Dossiers