Skip to content

Instantly share code, notes, and snippets.

@colemanfoley
Created September 25, 2012 17:17
Show Gist options
  • Save colemanfoley/3783235 to your computer and use it in GitHub Desktop.
Save colemanfoley/3783235 to your computer and use it in GitHub Desktop.
Numbers into Words recursively
module InWords
#The method for turning integers 1-19 into the appropriate strings.
def under20
array_under20 = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
return array_under20[self]
end
#The method for turning integers 20-99 into the appropriate strings.
def under100
_20_99 = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
first_part = _20_99[(self/10) - 2]
second_part = (self % 10).under20
return first_part + " " + second_part
end
#This method turns integers between 100 and 999 into words. For the number in the hundreds place, I just passed the number to the under10 method then added "hundred" to the end.
#For the numbers in the tens and ones place, I
def under1000
first_digit = (self/100).floor
first_part = first_digit.under20 + " hundred"
if self % 100 == 0
second_part = ""
else
second_part = " " + (self % 100).in_words
end
return first_part + second_part
end
def under1000000
first_digit = (self/1000).floor
first_part = first_digit.in_words + " thousand"
if self % 1000 == 0
second_part = ""
else
second_part = " " + (self % 1000).in_words
end
return first_part + second_part
end
def in_words
if (self < 20)
return self.under20
end
if (self > 19 && self < 100)
return self.under100
end
if (self > 99 && self < 1000)
return self.under1000
end
if (self > 999 && self < 1000000)
return self.under1000000
end
end
end
class Fixnum
include InWords
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment