Created
June 15, 2012 04:44
-
-
Save jessieay/2934705 to your computer and use it in GitHub Desktop.
quasi-recursively
This file contains hidden or 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 magic | |
ones_array = %w{ not_called one two three four five six seven eight nine ten} | |
tens_array = %w{ not_called not_called twenty thirty forty fifty sixty seventy eighty ninety} | |
teens_array = [ "" ] + %w{ one two three four five six seven eight nine ten eleven twelve | |
thirteen fourteen fifteen sixteen seventeen eighteen nineteen} | |
# if self == 0 | |
# return "zero" | |
# end | |
hundreds = self / 100 | |
two_digit = self % 100 | |
if two_digit < 20 | |
tens_word = teens_array[two_digit] | |
else | |
tens = two_digit / 10 | |
ones = two_digit % 10 | |
tens_word = tens_array[tens] | |
tens_word << " " + ones_array[ones] unless ones == 0 | |
end | |
if hundreds == 0 | |
tens_word | |
else | |
hundreds_word = ones_array[hundreds] + " hundred" | |
hundreds_word << " " + tens_word unless two_digit == 0 | |
hundreds_word | |
end | |
end | |
def in_words | |
big_ones = {1_000 => "thousand", 1_000_000 => "million", 1_000_000_000 => "billion", | |
1_000_000_000_000 => "trillion"} | |
last = ((self % 1_000).magic) unless self < 1000 | |
if self < 1000 | |
last = self.magic | |
end | |
if self / 1_000 != 0 | |
if self / 1_000_000 == 1_000_000 || self / 1_000 == 1_000_000|| self / 1_000 == 1_000 || self / 1_000 == 1_000_000_000 | |
thousands = "" | |
else | |
thousands = ((self / 1000) % 1000).magic + " " + big_ones[1_000] | |
end | |
else thousands = "" | |
end | |
if self / 1_000_000 != 0 | |
if self / 1_000_000 == 1_000_000 || self / 1_000_000 == 1_000 | |
millions = "" | |
else | |
millions = ((self / 1_000_000) % 1000).magic + " " + big_ones[1_000_000] | |
end | |
else millions = "" | |
end | |
if self / 1_000_000_000 != 0 | |
if self / 1_000_000_000 == 1_000 | |
billions = "" | |
else | |
billions = ((self / 1_000_000_000) % 1000).magic + " " + big_ones[1_000_000_000] | |
end | |
else billions = "" | |
end | |
if self / 1_000_000_000_000 != 0 | |
trillions = "one" + " " + big_ones[1_000_000_000_000] | |
else trillions = "" | |
end | |
final_number = "#{trillions} #{billions} #{millions} #{thousands} #{last}" | |
return final_number.split.join(" ").to_s | |
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