Created
November 23, 2015 00:00
-
-
Save ewhitebloom/a894095c5f58db5b788d to your computer and use it in GitHub Desktop.
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
TEENS = { | |
0 => 'Ten', | |
1 => 'Eleven', | |
2 => 'Twelve', | |
3 => 'Thirteen', | |
4 => 'Fourteen', | |
5 => 'Fifteen', | |
6 => 'Sixteen', | |
7 => 'Seventeen', | |
8 => 'Eighteen', | |
9 => 'Nineteen' | |
} | |
TENS = { | |
2 => 'Twenty', | |
3 => 'Thirty', | |
4 => 'Forty', | |
5 => 'Fifty', | |
6 => 'Sixty', | |
7 => 'Seventy', | |
8 => 'Eighty', | |
9 => 'Ninety' | |
} | |
ONES = { | |
1 => 'One', | |
2 => 'Two', | |
3 => 'Three', | |
4 => 'Four', | |
5 => 'Five', | |
6 => 'Six', | |
7 => 'Seven', | |
8 => 'Eight', | |
9 => 'Nine', | |
} | |
def integerToWord(int) | |
return unless (0..999).include?(int) | |
return 'Zero' if int == 0 | |
digits = int.to_s.chars.map(&:to_i) | |
result = [] | |
while digits.size > 0 | |
case digits.size | |
when 3 | |
result << ONES[digits.shift] + ' Hundred' | |
when 2 | |
if digits.first == 1 | |
result << TEENS[digits.last] | |
return result.join(' ') | |
else | |
result << TENS[digits.shift] | |
end | |
when 1 | |
result << ONES[digits.shift] | |
end | |
end | |
result.compact.join(' ') | |
end | |
# Also, works. Debately more clear. | |
def integerToWord2(int) | |
return unless (0..999).include?(int) | |
return 'Zero' if int == 0 | |
digits = int.to_s.chars.map(&:to_i) | |
result = [] | |
if digits.size == 3 | |
result << ONES[digits.shift] + ' Hundred' | |
end | |
if digits.size == 2 && digits.first == 1 | |
result << TEENS[digits.last] | |
return result.join(' ') | |
end | |
if digits.size == 2 | |
result << TENS[digits.shift] | |
end | |
if digits.size == 1 | |
result << ONES[digits.shift] | |
end | |
result.compact.join(' ') | |
end | |
def test(i) | |
puts "#{i}: #{integerToWord(i)}" | |
end | |
(0..999).each do |i| | |
test(i) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment