RosettaCodeData/Task/Number-names/Ruby/number-names.rb

61 lines
1.6 KiB
Ruby
Raw Permalink Normal View History

2013-04-10 23:57:08 -07:00
SMALL = %w(zero one two three four five six seven eight nine ten
eleven twelve thirteen fourteen fifteen sixteen seventeen
eighteen nineteen)
TENS = %w(wrong wrong twenty thirty forty fifty sixty seventy
eighty ninety)
BIG = [nil, "thousand"] +
%w( m b tr quadr quint sext sept oct non dec).map{ |p| "#{p}illion" }
def wordify number
2015-02-20 00:35:01 -05:00
case
when number < 0
2013-04-10 23:57:08 -07:00
"negative #{wordify -number}"
2015-02-20 00:35:01 -05:00
when number < 20
2013-04-10 23:57:08 -07:00
SMALL[number]
2015-02-20 00:35:01 -05:00
when number < 100
2013-04-10 23:57:08 -07:00
div, mod = number.divmod(10)
2015-02-20 00:35:01 -05:00
TENS[div] + (mod==0 ? "" : "-#{wordify mod}")
2013-04-10 23:57:08 -07:00
2015-02-20 00:35:01 -05:00
when number < 1000
2013-04-10 23:57:08 -07:00
div, mod = number.divmod(100)
2015-02-20 00:35:01 -05:00
"#{SMALL[div]} hundred" + (mod==0 ? "" : " and #{wordify mod}")
2013-04-10 23:57:08 -07:00
else
# separate into 3-digit chunks
chunks = []
div = number
while div != 0
div, mod = div.divmod(1000)
2015-02-20 00:35:01 -05:00
chunks << mod # will store smallest to largest
2013-04-10 23:57:08 -07:00
end
2015-02-20 00:35:01 -05:00
raise ArgumentError, "Integer value too large." if chunks.size > BIG.size
2013-04-10 23:57:08 -07:00
chunks.map{ |c| wordify c }.
2015-02-20 00:35:01 -05:00
zip(BIG). # zip pairs up corresponding elements from the two arrays
2013-04-10 23:57:08 -07:00
find_all { |c| c[0] != 'zero' }.
2015-02-20 00:35:01 -05:00
map{ |c| c.join ' '}. # join ["forty", "thousand"]
2013-04-10 23:57:08 -07:00
reverse.
2015-02-20 00:35:01 -05:00
join(', '). # join chunks
2013-04-10 23:57:08 -07:00
strip
end
end
2015-02-20 00:35:01 -05:00
data = [-1123, 0, 1, 20, 123, 200, 220, 1245, 2000, 2200, 2220, 467889,
23_000_467, 23_234_467, 2_235_654_234, 12_123_234_543_543_456,
987_654_321_098_765_432_109_876_543_210_987_654,
123890812938219038290489327894327894723897432]
data.each do |n|
2013-04-10 23:57:08 -07:00
print "#{n}: "
begin
puts "'#{wordify n}'"
rescue => e
puts "Error: #{e}"
end
end