Skip to content

Instantly share code, notes, and snippets.

@patbenatar
Created August 31, 2016 00:20
Show Gist options
  • Save patbenatar/2d3bb8e647163174662f62753f489a8e to your computer and use it in GitHub Desktop.
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
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
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