Hi there,
I’m trying to write a class which converts a number into letters like
so:
0 => -
1 => A
10 => J
27 => AA
… ad infinitum. My class looks like this at the moment (please don’t
laugh!)
def letter(number)
@index = number - 1
if @index == 0
return “-”
end
@index_string = “”
@index_array= []
while @index > 0 do
@remainder = @index%27
@index_array << @remainder
@index = @index/27
end
@index_array
@index_array.each do |i|
I’m sure there’s a better way to do this
@alphabet =
[“A”,“B”,“C”,“D”,“E”,“F”,“G”,“H”,“I”,“J”,“K”,“L”,“M”,“N”,“O”,“P”,“Q”,“R”,“S”,“T”,“U”,“V”,“W”,“X”,“Y”,“Z”]
@index_string << @alphabet[i-1]
end
return @index_string.reverse!
end
This works fine for the first round: 26 returns “Z”. But 27 returns “AZ”
because @index_array is [0,1]. I’d appreciate any help (and tips on how
to write tighter code!)