```From: Gavin Kistner
Sent: Thursday, June 07, 2007 12:10 PM
> From: bbiker [mailto:renard / nc.rr.com]
> Sent: Thursday, June 07, 2007 12:00 PM
>
> > I am not exactly sure what the OP was trying to do .. except that it
> > has to do with Columns in Excel. It does seems to me to be fairly
> > complicated. If this off topic, please excuse.
>
> [snip]
>
> > # method to convert from numeric column to alpha col
> > # accepts numeric column 1 through 256
> > # returns alpha column A through IV
> > # returns empty string on invalid input
> > def n2a_col(num_col)
> >
> > 	# verify that it in the range of 1 to 255
> > 	return nil if num_col < 1 || num_col > 256
> >
> > 	mostSD = num_col / 26  # SD = Significant Digit
> > 	leastSD = num_col % 26
> >
> > 	if leastSD == 0
> > 		mostSD -= 1
> > 		leastSD = 26
> > 	end
> >
> > 	leastSA = ('A'[0] + leastSD - 1 ).chr
> > 	mostSA  = mostSD > 0 ? ('A'[0] + mostSD - 1).chr : ''
> >
> >   mostSA + leastSA
> > end
>
> Not as efficient, but simpler:
>
> def n2a_col( num_col )
>   if (1..255).include?( num_col )
>     a = 'A'
>     ( num_col-1 ).times{ a = a.succ }
>     a
>   end
> end
>
> [ 0, 1, 2, 26, 27, 250, 255, 256 ].each{ |n|
>  puts "%3d => %s" % [ n, n2a_col( n ).inspect ]
> }
>
> #=>   0 => nil
> #=>   1 => "A"
> #=>   2 => "B"
> #=>  26 => "Z"
> #=>  27 => "AA"
> #=> 250 => "IP"
> #=> 255 => "IU"
> #=> 256 => nil

But speaking of efficiency, here's an auto-caching hash that only
calculates the column name once for each number. The only 'downside' is
that asking for the name of column 200 the first time fills in the
values for columns 199 down to the previously greatest column.

COL_NAME = Hash.new{ |h,n|
if n==1
h[n] = 'A'
elsif (2..255).include?( n )
h[n] = h[n-1].succ
end
}

[ 0, 1, 2, 26, 27, 250, 255, 256 ].each{ |n|
puts "%3d => %s" % [ n, COL_NAME[ n ].inspect ]
}

#=>   0 => nil
#=>   1 => "A"
#=>   2 => "B"
#=>  26 => "Z"
#=>  27 => "AA"
#=> 250 => "IP"
#=> 255 => "IU"
#=> 256 => nil

```