Names to numbers: Difference between revisions

no edit summary
No edit summary
Line 759:
-2 <==> minus two
0 <==> zero</pre>
 
=={{header|Ruby}}==
This solution uses "Number names" from [[Number_names#Ruby | here]]
{{trans|Python}}
<lang ruby>require 'Number_names'
 
def int_from_words(num)
words = num.downcase.gsub(/(,| and |-)/,' ').split
if words[0] =~ /(minus|negative)/ # or words[0] == 'negative'
negmult = -1
words.shift
else
negmult = 1
end
small, total = 0, 0
for word in words
case word
when *SMALL
small += SMALL.index(word)
when *TENS
small += TENS.index(word) * 10
when 'hundred'
small *= 100
when 'thousand'
total += small * 1000
small = 0
when *BIG
total += small * 1000 ** BIG.index(word)
small = 0
else
raise ArgumentError, "Don't understand %s part of %s" % [word, num]
end
end
negmult * (total + small)
end
 
# examples
for n in (-10000..10000).step(17)
raise unless n == int_from_words(wordify(n))
end
 
for n in 0...20
raise unless 13**n == int_from_words(wordify(13**n))
end
 
puts "##\n## These tests show <==> for a successful round trip, otherwise <??>\n##"
for n in [0, -3, 5, -7, 11, -13, 17, -19, 23, -29]
txt = wordify(n)
num = int_from_words(txt)
puts '%+4i <%s> %s' % [n, n==num ? '==' : '??', txt]
end
puts
 
n = 201021002001
loop do
txt = wordify(n)
num = int_from_words(txt)
puts '%12i <%s> %s' % [n, n==num ? '==' : '??', txt]
break if n==0
n /= -10
end</lang>
 
{{out}}
<pre>
</pre>
 
=={{header|Tcl}}==
Anonymous user