问题
How can I the get character sequence, for example "AA" from column index 26?
回答1:
Here's a recursive hash that will handle indexing for you:
index_hash = Hash.new {|hash,key| hash[key] = hash[key - 1].next }.merge({0 => "A"})
index_hash[26] #=> "AA"
The key here is the .next method, which when sent to a string, will return the alphabetically following string, e.g. "CD".next #=> "CE".
Could you clarify your first question?
回答2:
class Numeric
Alph = ("A".."Z").to_a
def alph
s, q = "", self
(q, r = (q - 1).divmod(26)) && s.prepend(Alph[r]) until q.zero?
s
end
end
(26+1).alph #=> "AA"
回答3:
c = "A"
26.times { c = c.next }
c # => "AA"
来源:https://stackoverflow.com/questions/13578555/convert-spreadsheet-column-index-into-character-sequence