Skip to content

Instantly share code, notes, and snippets.

@coderdan
Created February 1, 2016 00:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coderdan/ab80e59f183a5343356d to your computer and use it in GitHub Desktop.
Save coderdan/ab80e59f183a5343356d to your computer and use it in GitHub Desktop.
require 'rspec'
NUMBERS = {
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'
}
TENS = {
2 => 'twenty',
3 => 'thirty',
4 => 'fourty',
5 => 'fifty',
6 => 'sixty',
7 => 'seventy',
8 => 'eighty',
9 => 'ninety'
}
def number_to_words(num)
return nil if num == 0
return NUMBERS[num] if (1..15).include?(num)
return "#{NUMBERS[num % 10]}teen" if (16..19).include?(num)
return [ TENS[num / 10], NUMBERS[num % 10] ].join if num < 100
return [ "#{NUMBERS[num / 100]} hundred", number_to_words(num % 100) ].compact.join(' and ') if num < 1000
[ "#{NUMBERS[num / 1000]} thousand", number_to_words(num % 1000) ].compact.join(' ')
end
RSpec.describe 'number to words' do
it 'converts 0 to nil' do
expect(number_to_words(0)).to eq(nil)
end
NUMBERS.each_pair do |num, word|
it "converts #{num} to #{word}" do
expect(number_to_words(num)).to eq(word)
end
end
it 'converts 16 to sixteen' do
expect(number_to_words(16)).to eq('sixteen')
end
it 'converts 17 to seventeen' do
expect(number_to_words(17)).to eq('seventeen')
end
TENS.each_pair do |multiple, word|
it "converts #{multiple * 10} to #{word}" do
expect(number_to_words(multiple * 10)).to eq(word)
end
it "converts #{multiple * 10 + 5} to #{word}five" do
expect(number_to_words(multiple * 10 + 5)).to eq(word + 'five')
end
end
it 'converts 100 to one hundred' do
expect(number_to_words(100)).to eq('one hundred')
end
it 'converts 120 to one hundred and twenty' do
expect(number_to_words(120)).to eq('one hundred and twenty')
end
it 'converts 125 to one hundred and twentyfive' do
expect(number_to_words(125)).to eq('one hundred and twentyfive')
end
it 'converts 200 to two hundred' do
expect(number_to_words(200)).to eq('two hundred')
end
it 'converts 250 to two hundred and fifty' do
expect(number_to_words(250)).to eq('two hundred and fifty')
end
it 'converts 351 to three hundred and fiftyone' do
expect(number_to_words(351)).to eq('three hundred and fiftyone')
end
it 'converts 1000 to one thousand' do
expect(number_to_words(1000)).to eq('one thousand')
end
it 'converts 1276 to one thousand two hundred and seventysix' do
expect(number_to_words(1276)).to eq('one thousand two hundred and seventysix')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment