Created
June 28, 2012 06:17
-
-
Save dladowitz/3009470 to your computer and use it in GitHub Desktop.
Numbers to Words (up to 999) in ruby
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
module InWords | |
def in_words | |
ones = { | |
1 => "one", | |
2 => "two", | |
3 => "three", | |
4 => "four", | |
5 => "five", | |
6 => "six", | |
7 => "seven", | |
8 => "eight", | |
9 => "nine" } | |
teens = { | |
10 => "ten", | |
11 => "eleven", | |
12 => "twelve", | |
13 => "thirteen", | |
14 => "fourteen", | |
15 => "fifthteen", | |
16 => "sixteen", | |
17 => "seventeen", | |
18 => "eighteen", | |
19 => "nineteen" } | |
tens = { | |
0 => "", | |
2 => "twenty", | |
3 => "thirty", | |
4 => "fourty", | |
5 => "fifty", | |
6 => "sixty", | |
7 => "seventy", | |
8 => "eighty", | |
9 => "ninety" } | |
number_in_words = "" | |
first_digit = "" | |
second_digit = "" | |
third_digit = "" | |
second_and_third_digits = "" | |
case self.to_s.length | |
when 1 | |
puts "Num is single digit" | |
number_in_words = ones[self] | |
when 2 | |
puts "Num is double digits" | |
if number_in_words = teens[self] | |
puts "Num is in the Teens" | |
else | |
puts "Num is not in the Teens" | |
first_digit = self/10 | |
number_in_words = tens[first_digit] | |
if (self % 10) == 0 | |
puts "Num is a power of ten'" | |
else | |
puts "Num is not a power of ten'" | |
second_digit = self%10 | |
number_in_words << ones[second_digit] | |
end | |
end | |
when 3 | |
puts "Num is triple digits" | |
first_digit = (self/100) | |
number_in_words = ones[first_digit] + " hundred" | |
if (self % 100) == 0 | |
puts "Num is an even hundred" | |
else | |
# Checks to see if we need the 'teens' hash | |
second_and_third_digits = self%100 | |
if teens[second_and_third_digits] | |
puts "Num is in the Teens" | |
number_in_words << " and " + teens[second_and_third_digits] | |
else | |
puts "Num is not in the Teens" | |
second_digit = (self %100 /10) | |
number_in_words << " and " + tens[second_digit] | |
if (self % 100) == 0 | |
puts "Num is a 'ty'" | |
else | |
third_digit = (self %100 %10) | |
number_in_words << " " + ones[third_digit] | |
end | |
end | |
end | |
else | |
"That ain't no number between 1 and 999" | |
end | |
return number_in_words | |
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