Last active
December 16, 2015 13:08
-
-
Save stewartknapman/5439221 to your computer and use it in GitHub Desktop.
Turn a number into a letter.
Useful for formatting the numbering for alpha lists. Uses Words notation so when it reaches z it will continue aa, bb, cc, etc.
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
def number_to_letter(n=1) | |
nums = *'a'..'z' | |
nums[(n % 26) - 1] * ((n-1) / 26 + 1) | |
end | |
# Smart ass one line edition by @krolaw | |
# Doesn't use an array | |
def number_to_letter_revised(n=1) | |
('a'.ord+((n-1) % 26)).chr * ((n-1) / 26 + 1) | |
end | |
# Output the result for numbers 1 to 100 | |
(1..100).each{|i| puts "#{i} -> #{number_to_letter(i)}"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment