What I need to do is convert "22/11/2007" to
"twenty-two/eleven/two-thousand-seven" and then convert it back to
"22/11/2007", what I will be doing is building a plugin for Mephisto to
highjack my archive URIs to words over numbers and then converting it
back to Mephisto when it comes back in. Out as word in as number. That
way no major changes have to be made to the backend itself. It doesn't
have to add in the dashes since I can simply do that with split (" ")
and join ("-"). I did look into Linguistics but it is a one way
conversion, I need 2 way conversion. Thanks.
For 7 -> "seven" see:
http://www.rubyquiz.com/quiz25.html
The reverse would make a fun problem to solve, too.
Here, let me get you started:
ENGLISH_VALUE = {}
%w| zero one two three four five six seven eight nine ten eleven
twelve thirteen fourteen fifteen sixteen seventeen eighteen
nineteen |.each_with_index{ |word,i| ENGLISH_VALUE[word] = i }
%w| zero ten twenty thirty forty fifty sixty seventy eighty
ninety|.each_with_index{ |word,i| ENGLISH_VALUE[word] = i*10 }
ENGLISH_VALUE['hundred'] = 100
%w| one thousand million billion trillion|.each_with_index{ |word,i|
ENGLISH_VALUE[word] = 10**(i*3)
}
class Integer
def self.from_english( words )
values = words.downcase.split( /\W+/ ).map{ |word|
ENGLISH_VALUE[word]
}
# Put your magic here
end
end
TESTS = {
'one'=>1,
'seventy three'=>73,
'ninety nine'=>99,
'one hundred'=>100,
'one hundred one'=>101,
'one hundred twenty'=>120,
'three hundred sixty four'=>364,
'eight thousand five'=>8_005,
'forty-three thousand twelve'=>43_012,
'two billion one hundred thousand seventeen'=>2_000_100_117
}
TESTS.each{ |word,expected_value|
actual_value = Integer.from_english( word )
unless actual_value == expected_value
warn "From '#{word}', " <<
"expected: #{expected_value}, " <<
"actual: #{actual_value.inspect}"
end
}
#=> From 'forty-three thousand twelve', expected: 43012, actual: [40,
3, 1000, 12]
#=> From 'one hundred one', expected: 101, actual: [1, 100, 1]
#=> From 'ninety nine', expected: 99, actual: [90, 9]
#=> From 'one', expected: 1, actual: [1]
#=> From 'eight thousand five', expected: 8005, actual: [8, 1000, 5]
#=> From 'one hundred twenty', expected: 120, actual: [1, 100, 20]
#=> From 'two billion one hundred thousand seventeen', expected:
2000100117, actual: [2, 1000000000, 1, 100, 1000, 17]
#=> From 'three hundred sixty four', expected: 364, actual: [3, 100,
60, 4]
#=> From 'one hundred', expected: 100, actual: [1, 100]
#=> From 'seventy three', expected: 73, actual: [70, 3]