Created
August 31, 2016 00:20
-
-
Save patbenatar/2d3bb8e647163174662f62753f489a8e to your computer and use it in GitHub Desktop.
Just in case you ever find yourself needing to generate spreadsheet column identifiers from an arbitrary index
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
class SheetColumnIdentifiers | |
def initialize | |
@alphabet = ('A'..'Z').to_a | |
end | |
def [](index) | |
return alphabet[index] if index < alphabet.length | |
pad_index = (index / alphabet.length) - 1 | |
self[pad_index] + self[index % alphabet.length] | |
end | |
private | |
attr_reader :alphabet | |
end |
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
RSpec.describe SheetColumnIdentifiers do | |
context 'index less than 26' do | |
it 'returns the alphabet character at given index' do | |
expect(subject[0]).to eq 'A' | |
expect(subject[25]).to eq 'Z' | |
end | |
end | |
context 'index greater than 26, causing a two digit alpha ID' do | |
it 'loops over itself, concatenating to create a spreadsheet row ID' do | |
expect(subject[26]).to eq 'AA' | |
expect(subject[28]).to eq 'AC' | |
end | |
end | |
context 'index much greater than 26, causing first alpha digit to increment' do | |
it 'loops over itself, concatenating to create a spreadsheet row ID' do | |
expect(subject[52]).to eq 'BA' | |
expect(subject[53]).to eq 'BB' | |
end | |
end | |
context 'index so great that it requires 3 alpha digits' do | |
it 'loops over itself, concatenating to create a spreadsheet row ID' do | |
expect(subject[702]).to eq 'AAA' | |
expect(subject[703]).to eq 'AAB' | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment