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\
class Numeric
# 'z' is placed in the begining of the array because 26 % 26 is 0 not 26
Alph = ['z'] + ("a".."y").to_a
def to_alph
# if self is 0 or negative return a blank string.
# this is also used to end the recursive chain of to_alph calls
# so don't replace this with raising an error or returning anything else
return '' if self < 1
# (otherwise) return two concatenated strings:
# the right side is the letter for self modules 26
# the left side is comprised of:
# 1. minus one, because this is not a zero-based numbering system.
# therefore, round numbers (26, 52...) should return one digit 'z'
# instead of two digits 'aa' or 'ba'.
# 2. divide by 26 and call to_alph on that.
# this repeats recursively for every digit of the final string,
# plus once more that will return '' to end the recursion chain.
return ((self - 1) / 26).to_alph + Alph[self % 26]
end
end
I liked this answer from: https://stackoverflow.com/a/17785576/514483
number.to_s(26).tr("0123456789abcdefghijklmnopq", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")