Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Roo::Utils.number_to_letter #308

Merged
merged 2 commits into from
Apr 9, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions lib/roo/utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ module Roo
module Utils
extend self

LETTERS = ('A'..'Z').to_a

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe freeze it


def split_coordinate(str)
@split_coordinate ||= {}

Expand All @@ -27,16 +29,14 @@ def split_coord(s)

# convert a number to something like 'AB' (1 => 'A', 2 => 'B', ...)
def number_to_letter(num)
results = []
num = num.to_i
result = ""

while (num > 0)
mod = (num - 1) % 26
results = [(65 + mod).chr] + results
num = ((num - mod) / 26)
until num.zero?
num, index = (num - 1).divmod(26)
result.prepend(LETTERS[index])
end

results.join
result
end

def letter_to_number(letters)
Expand Down
2 changes: 1 addition & 1 deletion spec/lib/roo/utils_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
subject { described_class }

context '#number_to_letter' do
('A'..'Z').to_a.each_with_index do |letter, index|
described_class::LETTERS.each_with_index do |letter, index|
it "should return '#{ letter }' when passed #{ index + 1 }" do
expect(described_class.number_to_letter(index + 1)).to eq(letter)
end
Expand Down