Excel Series Decoder in Ruby 6

Posted by Ben Poweski Tue, 04 Mar 2008 18:16:00 GMT

A co-worker of mine was writing a little script to parse an excel file that contained various network addresses and run various test cases against it. He was stumped on the algorithm how to decoded excel headers to specific indexes. While at first glance this looks like a simple problem, it ended up being more difficult than we thought. My co-worker approached the problem using a procedural approach, this ended up yielding a few nasty loops…far from elegant. The end result ended up being rather easy once the approach was modified to use recursion.

My Solution

require 'test/unit'

def to_excel(i)
  case i
  when 0
    return ''
  when 1..26
    return ('A'..'Z').to_a.at(i - 1)
  else
    q, r = (i - 1).div(26), (i - 1) % 26
    return "#{to_excel(q)}#{to_excel(r + 1)}"
  end
end

class ExcelNumberSeriesTest < Test::Unit::TestCase
  def test_simple
    assert_equal 'A', to_excel(1)
    assert_equal '', to_excel(0)
    assert_equal 'Z', to_excel(26)
  end

  def test_doubles
    assert_equal 'AA', to_excel(27)
    assert_equal 'AB', to_excel(28)
    assert_equal 'AZ', to_excel(52)
  end
end
Comments

Leave a comment

  1. emailextractor about 3 years later:

    What about the others?

  2. krzyzowki about 3 years later:

    Great blog post, I have been waiting for that

  3. linux about 3 years later:

    Great blog post, I have been waiting for that

  4. Joseph Raymond over 3 years later:

    which language is that . I am pretty sure it is not vb. Otherwise it will break on

    return ”

    SO something similar to VB syntax I guess

  5. Juliet Jess over 3 years later:

    Thats a nice way to decode. Most of the cases recursion gives simple solution. But breaking the recursion is the most important one.

  6. Used Cars In Chennai almost 4 years later:

    Recursion is always simple and easy to read. However if the break or ending logic is not working. It will become endless. So necessary action to be taken care

Comments