Skip to content

Commit

Permalink
Merge pull request #308 from ilyasgaraev/number-to-letter
Browse files Browse the repository at this point in the history
Update Roo::Utils.number_to_letter
  • Loading branch information
stevendaniels committed Apr 9, 2016
2 parents 8143da4 + 908d049 commit b19c4ff
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 8 deletions.
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

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

0 comments on commit b19c4ff

Please sign in to comment.