While reading through another question here, on creating a URL shortening service, it was suggested to take the ID of the row, and then convert it to base 62 (0 to 9, a to z, and A to Z). Is there a standard function to accomplish this in Ruby?
Edit: Not sure if I was clear enough.
Something like this: 123456.radix(62)
should give the base 62 of 123456.
I'm thinking of writing one, if it isn't already there.
The to_s method in Ruby integer classes has an optional parameter specifying the base, something like:
123456.to_s(16)
However, it only accepts values from 2 to 36 as the radix.
This snippet might be a good starting place if you want to write your own encoder. There's also a base62 Ruby Gem that adds methods for encoding and decoding in base62.
Since I recently needed to use radixes in Ruby, and since this is the first result for 'Ruby radix', I thought I would point out that there is now a gem for working with radixes. Here is how to code the OP's example using it:1
require 'radix'
SIXTYTWO = ('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a
123456.b(62).to_s(SIXTYTWO)
1 The SIXTYTWO
array is needed because the gem doesn't make any assumptions about which characters to use to encode the result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With