Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
english_number created by jmkoni - https://repl.it/@jmkoni/englishnumber
class NumberPrinter
ONES = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
TEENS = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
TENS = ["ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
TRANSLATION = { hundred: 100, thousand: 1000, million: 1000000, billion: 1000000000}
attr_accessor :number
def initialize(number)
@number = number
end
def print_english_number
print_number(@number)
end
private
def print_number(number)
full_number = ""
full_number += "negative " if number < 0
number = number.abs
if number < 10
full_number += get_ones(number)
elsif number < 20
full_number += get_teens(number)
elsif number < 100
full_number += get_tens(number)
else
full_number += get_greater(number)
end
full_number
end
def get_ones(number)
ONES[number]
end
def get_teens(number)
TEENS[number - 10]
end
def get_tens(number)
tens = number / 10
remainder = get_remainder(number, 10)
TENS[tens - 1] + " " + remainder
end
def get_greater(number)
TRANSLATION.each do |size, divisor|
if right_divisor?(number, divisor)
text = print_number(number / divisor)
remainder = get_remainder(number, divisor)
return text + " " + size.to_s + " " + remainder
end
end
end
def right_divisor?(number, divisor)
less_thousands?(number, divisor) or thousands_or_more?(number, divisor)
end
def less_thousands?(number, divisor)
divisor < 1000 and (1..9).include?(number / divisor)
end
def thousands_or_more?(number, divisor)
divisor >= 1000 and (1...1000).include?(number / divisor)
end
def get_remainder(number, divisor)
mod = number % divisor
remainder = mod > 0 ? print_number(mod) : 0
end
end
num = NumberPrinter.new(1927838982)
puts num.print_english_number
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.