Ruby – how to turn integers into base36 for urls

Here’s a nice trick for turning long integers into much shorter “tinyurl” style strings.

12345.to_s(36)
=> "9ix"
"9ix".to_i(36)
=> 12345

Technically what’s happening here is Ruby is turning the Base-10 Integer into a Base-36 alphanumeric representation of that number.

This is the trick that reddit.com uses for creating smaller urls that correspond to an integer-based record in their cassandra database.

Here’s another trick for ya- You can use the same method to create shortented URLs that are consistent and unique:

"http://chris3000.com".hash.abs.to_s(36)
 => "vaniclb8g7wm"
"http://www.google.com/?q=this+is+a+long+query+in+google".hash.abs.to_s(36)
 => "kod59h8xj2sg"