Convert spreadsheet column index into character sequence

断了今生、忘了曾经 提交于 2019-12-01 12:56:35

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!