Skip to content

Instantly share code, notes, and snippets.

@jayrobin
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jayrobin/9631274 to your computer and use it in GitHub Desktop.
Save jayrobin/9631274 to your computer and use it in GitHub Desktop.
Prompts for a number and outputs the same number in English
# convert a triplet (0-999) into english words representing the value
def triplet_to_words(triplet)
ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
left_digit = triplet / 100
middle_digit = (triplet % 100) / 10
right_digit = triplet % 10
word = ""
word << "#{ones[left_digit]} hundred " if left_digit > 0
word << "#{teens[right_digit]} " if middle_digit == 1
word << "#{tens[middle_digit]} " if middle_digit > 1
word << "#{ones[right_digit]} " unless middle_digit == 1
word
end
# converts any number into english words representing the value
def number_to_words(number, magnitude = 0)
return "" if number == 0 # base case
illions = ["", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion"]
word = ""
word << number_to_words(number / 1000, magnitude + 1) if number > 1000
word << triplet_to_words(number % 1000)
word << "#{illions[magnitude]} " if magnitude > 0
word
end
print "Enter a number: "
number = gets.chomp.to_i
puts number_to_words(number)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment