class Integer
126620.to_word # => “one hundred twenty six thousand six hundred twenty”
1.to_word # => “one”
@example
numbers to words in various languages, including English.
into their word representations. It provides methods for converting
This class extends the Integer class with methods to convert numbers
def additional_tests(numbers)
def additional_tests(numbers) teen_to_word(numbers) digit_to_word(numbers) tens_place_to_word(numbers) true end
def append_place(word, place, numbers)
-
(String)
- The word with the appropriate place value appended.
Parameters:
-
numbers
(Hash
) -- A hash containing number words. -
place
(Integer
) -- The place value (e.g., hundreds, thousands). -
word
(String
) -- The word representation of the number.
def append_place(word, place, numbers) places = numbers[:places] if place > 2 word + ' ' + places[place] else word end end
def digit_to_word(numbers)
-
(String)
- The word representation of the number.
Parameters:
-
numbers
(Hash
) -- A hash containing number words.
def digit_to_word(numbers) if zero? '' else numbers[:digits][self] end end
def hundred_to_word(place = 0, numbers)
def hundred_to_word(place = 0, numbers) if zero? '' elsif self < 10 append_place(digit_to_word(numbers), place, numbers) elsif self < 20 append_place(teen_to_word(numbers), place, numbers) elsif self < 100 append_place(tens_place_to_word(numbers), place, numbers) else hundreds = self / 100 tens = self % 100 if tens.zero? append_place(hundreds.digit_to_word(numbers) + " #{numbers[:places][2]}", place, numbers) else append_place(hundreds.digit_to_word(numbers) + " #{numbers[:places][2]} " + tens.tens_place_to_word(numbers), place, numbers) end end end
def teen_to_word(numbers)
-
(String)
- The word representation of the number.
Parameters:
-
numbers
(Hash
) -- A hash containing number words.
def teen_to_word(numbers) if self < 10 digit_to_word(numbers) elsif self < 20 numbers[:teens][self - 10] else tens_place_to_word(numbers) end end
def tens_place_to_word(numbers)
-
(String)
- The word representation of the number.
Parameters:
-
numbers
(Hash
) -- A hash containing number words.
def tens_place_to_word(numbers) if self > 19 tens = self / 10 ones = self % 10 ten = numbers[:tens][tens - 2] ten + (ones.zero? ? '' : ' ' + ones.digit_to_word(numbers)) else teen_to_word(numbers) end end
def to_word(numbers)
1.to_word # => "one"
Turn a number into the word representation of that number.
def to_word(numbers) tmp = self / 1000 final = (self % 1000).hundred_to_word(2, numbers) place = 3 # special-case the tens and below until tmp.zero? final = (tmp % 1000).hundred_to_word(place, numbers) + ' ' + final place += 1 tmp /= 1000 end final == '' ? 'zero' : final.sub(/\s+$/, '') end