From: Rob Date: 2006-03-08T11:13:42+09:00 Subject: Re: Indexing system - ruby newbie On 2006-03-03, Malte Milatz wrote: > > > Adam Groves schrieb: >> I'm trying to write a class which converts a number into letters like >> so: >> 0 => - >> 1 => A >> 10 => J >> 27 => AA > > Only after reading the other posts, I realized you want Y, Z, AA, AB, AC > and not Y, Z, AA, BB, CC, which is what is produced by this: > > def letter(i) > return '-' if i < 1 > ('A'..'Z').to_a.at(i%26 - 1) * ((i-1)/26 + 1) > end > > Malte could add one method to Integer and avoid a separate class. (_to_aa is a helper that works on 0..25 nstead of 1..26) eg puts 10.to_aa, (10**1000).to_aa class Integer def to_aa # (1..26) to (A..Z) if (self < 1) '-' else (self-1)._to_aa end end protected def _to_aa # helper (0..25) to (A..Z) if (self < 26) (self+?A).chr else ((self/26)-1)._to_aa+(self%26)._to_aa end end end