Here’s a little trick I discovered about a year ago. The Integer#to_s method takes an argument to change the base (it defaults to base 10 of course). The highest base you can use is 36, which is [a-z0-9]. There are many names for base 36, including the proper sexatrigesimal, the common hextridecimal, and the more modern alphadecimal.

Combined with the String#hash and Time#hash methods, you can get sweet little TinyUrl style hashes.

check it:

# timestamp
>> DateTime.now.hash.abs.to_s(36)
=> "5ynfka" 

# invite code
>> "joe@momma.org".hash.to_s(36)
=> "emhs98" 

Not sure of the ultimate-in-the-entire-universe uniqueness of this type of hash, which I believe is based on some simple XORs… anyone care to comment?

2 Responses to “alphadecimal (base 36) hashes in ruby”

  1. Jack Danger Canty Says:

    I didn't realize until this post just how simple url-shortening and re-lengthening could be:

    1234567891012345.tos(36) == 1234567891012345.tos(36).to_i(36)

    Thanks!

  2. Senthil Nayagam Says:

    wow,

    it was simple, I was writing a far longer method to do it

Sorry, comments are closed for this article.