Skip to content

Instantly share code, notes, and snippets.

@kimyoutora
Created February 11, 2012 00:45
Show Gist options
  • Save kimyoutora/1794576 to your computer and use it in GitHub Desktop.
Save kimyoutora/1794576 to your computer and use it in GitHub Desktop.
Say a number string in English
THOUSANDS = ['', 'thousand', 'million', 'billion']
NUMS = {
"0" => '',
"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',
"20" => 'twenty',
"30" => 'thirty',
"40" => 'fourty',
"50" => 'fifty',
"60" => 'sixty',
"70" => 'seventy',
"80" => 'eighty',
"90" => 'ninty'
}
def say_thousand(str)
return "" if str.empty?
if NUMS[str]
return NUMS[str]
elsif str.size == 3
if str[0..0] == "0"
return say_thousand(str[1..-1])
else
return NUMS[str[0..0]] + " hundred " + say_thousand(str[1..-1])
end
else
if str[0..0] == "0"
return say_thousand(str[1..-1])
else
return "#{NUMS[str[0..0] + "0"]} " + say_thousand(str[1..-1])
end
end
end
def split_thousand(str)
length = str.size
thousands = []
num_leading_digits = length % 3
leading_digits = str[0...num_leading_digits]
thousands << leading_digits unless leading_digits.empty?
thousands + str[num_leading_digits..-1].scan(/.{3}/)
end
def say(str)
return "zero" if str == '0'
result = ""
thousands = split_thousand(str)
(0..(thousands.size - 1)).each do |i|
result += say_thousand(thousands[i]) + " #{THOUSANDS[thousands.size - 1 - i]} "
end
return result
end
puts say("90501")
puts say("9999999")
puts say("1293871985")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment