Pergunta

I need to implement a decimal to chars converter. I have 26 chars available, so it's about converting an integer to base 26 system and then, changing each number to it's alphabet counterpart. I don't want to use the characters 0-9 in the final result string. I can use to_s() method and this is how it goes:

82.to_s(26)  #=> "34" / which gives me "de"
120.to_s(26)  #=> "4g" / which should give me "aep", but it's not

Ruby to_s() method returns a value in a format that is not helpful. Number 82 is converted fine, but conversion of 120 returns a value I have no idea how to handle.

Could anyone explain how I can make the 120 convertion (as an example) return aep equivalent? In other words, how to convert from decimal base to 26 but without using numbers in output?

Foi útil?

Solução

Ruby's Fixnum#to_s( base ) and String#to_i( base ) are for representing numbers in different bases. You cannot use arbitrary characters with them though, they are designed to be compatible with conventions for hex and base64 amongst other things.

If you were not converting to a different base, but simply encoding decimal digits as letters and back, then a simple substitution would be all you needed:

46.to_s.tr( "0123456789", "abcdefghijk" )
=> "eg"

"eg".tr( "abcdefghijk", "0123456789" ).to_i
=> 46

So, if you want to do both, and use a-z to represent your number in base 26:

46.to_s(26).tr( "0123456789abcdefghijklmnopq", "abcdefghijklmnopqrstuvwxyz" )
=> "bu"

"bu".tr( "abcdefghijklmnopqrstuvwxyz", "0123456789abcdefghijklmnopq" ).to_i(26)
=> 46
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top