Created
March 8, 2016 20:31
-
-
Save MProuts/df2b719ec9dfeab6a0ff to your computer and use it in GitHub Desktop.
Ruby method to convert zero-based indices into excel column names (like, "AAB").
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'minitest/autorun' | |
# Turns an zero-based index into an excel column name | |
def excel_column_name(i) | |
digits = ("A".."Z").to_a | |
return digits[i] if i < 26 | |
"#{excel_column_name(i/26 - 1)}#{excel_column_name(i % 26)}" | |
end | |
class ExcelColumnNameTest < Minitest::Test | |
def test_n_less_than_26 | |
assert_equal("G", excel_column_name(7 - 1)) | |
end | |
def test_n_greater_than_26 | |
assert_equal("AA", excel_column_name(27 - 1)) | |
assert_equal("AZ", excel_column_name(52 - 1)) | |
end | |
def test_two_excel_digits | |
assert_equal("BA", excel_column_name(52)) | |
assert_equal("BZ", excel_column_name(77)) | |
end | |
def test_three_excel_digits | |
assert_equal("ZA", excel_column_name(26 * 26)) | |
assert_equal("ZZ", excel_column_name(26 * 26 + 26 - 1)) | |
assert_equal("AAA", excel_column_name(26 * 26 + 26)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment