I would like to generate a sequence of letters i.e. "A", "DE" "GJE", etc. that correspond to a number. The first 26 are pretty easy so 3 returns "C", 26 returns "Z", and 27 would return "AA", 28 "AB", and so on.
The thing I can't quite figure out is how to do this so it will handle any number passed in. So if I pass in 4123 I should get back some combination of 3 letters since (26 * 26 * 26) allows for up to +17,000 combinations.
Any suggestions?
Strings do have a
succ
method so they are usable in a Range. The successor to "Z" happens to be "AA", so this works:Based on sawa's answer, I wanted a method that worked independently, albeit recursively, to achieve the desired outcome:
A tweak on @sawa original answer for Ruby 2.0 since I couldn't get his to work as is:
and here it is going in reverse from string to integer:
Usage:
I liked this answer from: https://stackoverflow.com/a/17785576/514483