Skip to content

Instantly share code, notes, and snippets.

@jingoro
Created October 3, 2012 02:58
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 jingoro/3824690 to your computer and use it in GitHub Desktop.
Save jingoro/3824690 to your computer and use it in GitHub Desktop.
Number words to number
#!/usr/bin/env rspec
require 'rubygems'
require 'bundler/setup'
require 'rspec'
class Convert
MAPPING = {
# singles
'zero' => 0,
'one' => 1,
'two' => 2,
'three' => 3,
'four' => 4,
'five' => 5,
'six' => 6,
'seven' => 7,
'eight' => 8,
'nine' => 9,
'ten' => 10,
# teens
'eleven' => 11,
'twelve' => 12,
'thirteen' => 13,
'fourteen' => 14,
'fifteen' => 15,
'sixteen' => 16,
'seventeen' => 17,
'eighteen' => 18,
'nineteen' => 19,
# tens
'twenty' => 20,
'thirty' => 30,
'forty' => 40,
'fifty' => 50,
'sixty' => 60,
'seventy' => 70,
'eighty' => 80,
'ninety' => 90,
# bigger numbers
'hundred' => 100,
'thousand' => 1000,
'million' => 1000000
}
THOUSANDS = {
'thousand' => true,
'million' => true,
}
def self.to_number(words)
parts = words.split(/[-,\s]+/)
result = 0
accum = 0
while true
last_word = parts.shift
next if last_word == 'and'
last = MAPPING[last_word]
raise "Unknown word #{last_word}" unless last
if last_word == 'hundred'
accum = 1 if accum == 0
accum *= 100
elsif THOUSANDS[last_word]
accum = 1 if accum == 0
result += accum * last
accum = 0
else
accum += last
end
return result + accum if parts.size == 0
end
end
end
describe Convert do
begin
<<-EOF
three = 3
fourteen = 14
fifty two = 52
eight hundred sixty-nine = 869
thirteen hundred = 1300
four million, thirty two = 4000032
hundred seventy three million, two hundred five thousand, three hundred seven = 173205307
EOF
end.strip.split("\n").each do |line|
words, number = line.split('=')
words.strip!; number.strip!
it "'#{words}' should == #{number}" do
Convert.to_number(words).should == number.to_i
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment