Skip to content

Instantly share code, notes, and snippets.

@mfpiccolo
Last active December 11, 2015 10:08
Show Gist options
  • Save mfpiccolo/4584180 to your computer and use it in GitHub Desktop.
Save mfpiccolo/4584180 to your computer and use it in GitHub Desktop.
This program turns Integers into english.
class Fixnum
def in_words
#defining all the possible options for numbers < 1000
first_twenty = { 0 => "Zero", 1 => "One", 2 => "Two", 3 => "Three", 4 => "Four", 5 => "Five", 6 => "Six", 7 => "Seven",
8 => "Eight", 9 => "Nine", 10 => "Ten", 11 => "Eleven", 12 => "Twelve", 13 => "Thirteen", 14 => "Fourteen",
15 => "Fifteen", 16 => "Sixteen", 17 => "Seventeen", 18 => "eighteen", 19 => "Nineteen" }
tens = { 2 => "Twenty", 3 => "Thirty", 4 => "Fourty", 5 => "Fifty", 6 => "Sixty", 7 => "Seventy", 8 => "Eighty",
9 => "Ninety" }
if ((self < 20) && (self.is_a? Integer))
first_twenty[self] #
else number_string = self.to_s.split(//)
if number_string.length == 2 #if number is less than 99
tens[number_string[0].to_i] + "-" + first_twenty[number_string[1].to_i]
elsif number_string.length == 3 #if number is more that 99
if number_string[1].to_i == 1 #exception for numbers in the hundreds with tens place < 20
exception_1 = number_string[1] << number_string[2]
first_twenty[number_string[0].to_i] + "-Hundred" + " and " + first_twenty[exception_1.to_i]
elsif number_string[2].to_i == 0
first_twenty[number_string[0].to_i] + "-Hundred" + " and " + tens[number_string[1].to_i]
else
first_twenty[number_string[0].to_i] + "-Hundred" + " and " + tens[number_string[1].to_i] + "-" + first_twenty[number_string[2].to_i]
end
end
end
end
end
#unit tests
puts "'#{0.in_words}' should be 'Zero'"
puts "'#{4.in_words}' should be 'Four'"
puts "'#{9.in_words}' should be 'Nine'"
puts "'#{13.in_words}' should be 'Thirteen'"
puts "'#{22.in_words}' should be 'Twenty-Two'"
puts "'#{37.in_words}' should be 'Thirty-Seven'"
puts "'#{137.in_words}' should be 'One-Hundred and Thirty-Seven'"
puts "'#{287.in_words}' should be 'Two-Hundred and Eighty-Seven'"
puts "'#{396.in_words}' should be 'Three-Hundred and Ninety-Six'"
puts "'#{420.in_words}' should be 'Four-Hundred and Twenty'"
puts "'#{511.in_words}' should be 'Five-Hundred and Eleven'"
puts "'#{613.in_words}' should be 'Six-Hundred and Thirteen'"
puts "'#{750.in_words}' should be 'Seven-Hundred and Fifty'"
puts "'#{819.in_words}' should be 'Eight-Hundred and Nineteen'"
puts "'#{999.in_words}' should be 'Nine-Hundred and Ninety-Nine'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment