Skip to content

Instantly share code, notes, and snippets.

@stewartknapman
Last active December 16, 2015 13:08
Show Gist options
  • Save stewartknapman/5439221 to your computer and use it in GitHub Desktop.
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.
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