Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a radix function in ruby?

Tags:

ruby

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.

like image 397
user61734 Avatar asked May 18 '09 20:05

user61734


2 Answers

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.

like image 145
Firas Assaad Avatar answered Sep 29 '22 23:09

Firas Assaad


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.

like image 29
Abe Voelker Avatar answered Sep 29 '22 23:09

Abe Voelker