Created
July 12, 2013 03:17
-
-
Save keccers/5981150 to your computer and use it in GitHub Desktop.
Refactoring For Thomas: Small Numbers To Words
Helping a fellow DBC student.
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
NUMBERS_DICTIONARY = { 100 => "hundred", | |
90 => "ninety", | |
80 => "eighty", | |
70 => "seventy", | |
60 => "sixty", | |
50 => "fifty", | |
40 => "forty", | |
30 => "thirty", | |
20 => "twenty", | |
19 => "nineteen", | |
18 => "eighteen", | |
17 => "seventeen", | |
16 => "sixteen", | |
15 => "fifteen", | |
14 => "fourteen", | |
13 => "thirteen", | |
12 => "twelve", | |
11 => "eleven", | |
10 => "ten", | |
9 => "nine", | |
8 => "eight", | |
7 => "seven", | |
6 => "six", | |
5 => "five", | |
4 => "four", | |
3 => "three", | |
2 => "two", | |
1 => "one", | |
0 => ""} | |
def small_num_to_english(n) # n needs to be < 1000 | |
literal_number = "" #this is an empty string that will eventually become our literal number | |
if n > 100 | |
literal_number << NUMBERS_DICTIONARY[n/100] + " hundred " #pushes the number of hundreds to our string | |
n%=100 #reassigns the value of n to what's left of the number | |
remainder = n%10 #gets the ones digit | |
tens = n-remainder #gets the tens digit | |
literal_number << NUMBERS_DICTIONARY[tens] + " " #pushes those numbers to the string | |
literal_number << NUMBERS_DICTIONARY[remainder] | |
elsif n > 20 | |
remainder = n%10 #gets the ones digit | |
tens = n-remainder #gets the tens digit | |
literal_number << NUMBERS_DICTIONARY[tens] + " " #pushes those numbers to the string | |
literal_number << NUMBERS_DICTIONARY[remainder] | |
else | |
literal_number << NUMBERS_DICTIONARY[n] | |
end | |
literal_number | |
end | |
#DRIVER | |
puts small_num_to_english(45) | |
puts small_num_to_english(145) | |
puts small_num_to_english(999) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment