From: Rob Biedenharn Date: 2007-11-02T02:27:23+09:00 Subject: Re: Number to alpha letter On Nov 1, 2007, at 12:24 PM, Parv G. wrote: > Hi, > > Is there an out of box utility to convert a number to an alphabet > letter, like a to_alpha()? > > I'm trying to write the content of an array to a row in excel > worksheet. > > Thanks, > Parv This should get you started. It doesn't exactly work because it goes (with _ meaning a space) 'y', 'z', 'a_', 'aa', 'ab', but it's the right kind of idea (although the translation args should probably be expanded inline). The funkiness arises from the right-most position acting like base 26, but the other positions acting more like base 27. class Integer def to_column self.to_s(27).tr((('0'..'9').to_a + ('a'..'q').to_a).join(''), ([' ']+('a'..'z').to_a).join('')) end end You could either ignore the issue if you only had to deal with 26 or fewer columns: ('a'..'z').to_a[self-1] or split the value (which when I started to write out the pseudo-ruby looked so easy that I fixed my fence-post error and made it work): class Integer def to_column return 'a' if zero? upper, lower = self.divmod 26 unless upper.zero? column = (upper - 1).to_column else column = '' end column << (?a + lower).chr end end I think I'll have to tuck that away somewhere that I'll be able to find it again. -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com