Skip to content

Instantly share code, notes, and snippets.

@rust

rust/numerals.rb

Created Jun 2, 2012
Embed
What would you like to do?
English Numerals
#!/usr/bin/env ruby
require 'pp'
num = ARGV[0]
num = num.to_i
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',
16 => 'sixteen',
17 => 'seventeen',
18 => 'eighteen',
19 => 'nineteen',
20 => 'twenty',
30 => 'thirty',
40 => 'fourty',
50 => 'fifety',
60 => 'sixty',
70 => 'seventy',
80 => 'eighty',
90 => 'ninety',
}
def numerals(num)
return '' unless num
number = "%04d" % num
thousand = number[0]
hundered = number[1]
remains = number[2..3]
thousand = thousand.to_i
hundered = hundered.to_i
remains = remains.to_i
thousand_text = if thousand == 0
''
elsif thousand == 1
NUMBERS[thousand] + ' thousand'
else
NUMBERS[thousand] + ' thousands'
end
hundered_text = if hundered == 0
''
elsif hundered == 1
NUMBERS[hundered] + ' hundered'
else
NUMBERS[hundered] + ' hundereds'
end
remains_text = if remains == 0
''
elsif NUMBERS[remains]
NUMBERS[remains]
else
second, first = remains.to_s.split(//)
second = second.to_i * 10
first = first.to_i
"%s-%s" % [NUMBERS[second], NUMBERS[first]]
end
numerals_text = thousand_text
numerals_text += ' and ' unless thousand_text.empty?
numerals_text += hundered_text
numerals_text += ' and ' unless hundered_text.empty?
numerals_text += remains_text
numerals_text
end
puts numerals(ARGV[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.