【问题标题】:Convert spreadsheet column index into character sequence将电子表格列索引转换为字符序列
【发布时间】:2018-10-13 20:20:08
【问题描述】:

如何从列索引26获取字符序列,例如"AA"

【问题讨论】:

    标签: ruby spreadsheet


    【解决方案1】:

    这是一个递归哈希,它将为您处理索引:

    index_hash = Hash.new {|hash,key| hash[key] = hash[key - 1].next }.merge({0 => "A"})
    index_hash[26] #=> "AA"
    

    这里的关键是.next 方法,当发送到一个字符串时,将返回按字母顺序排列的字符串,例如"CD".next #=> "CE".

    你能澄清你的第一个问题吗?

    【讨论】:

      【解决方案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"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多