Hi,
I'm a junior software engineer who has been blessed with the gift of
Ruby as my introductory language. However, I'm a little anxious about a
coding test I have been asked to do....convert numbers to english words.
My solution is below which I was pretty pleased with...but I have to
present it and explain what it is that I could have done better. I was
hoping some of you could take a look and offer your opinions?
$hash = Hash[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
=>"forty", 50 => "fifty", 60 => "sixty", 70 => "seventy", 80 =>"eighty",
90 => "ninety", 100 => "hundred", 1000 => "thousand"]
class Integer
def to_words
str = ""
num = self
if num >= 1000000
millions = num/1000000
str += millions.to_words + " million"
str += " "
num = num - millions*1000000
end
if num >= 1000
thousands = num/1000
str += thousands.to_words + " thousand "
num = num - thousands*1000
end
if num >= 100
hundreds = num/100
str += $hash[hundreds] + " hundred"
if (num-hundreds*100) > 0
str += " and "
end
num = num - hundreds*100
end
if num > 0
if num <= 19
str += $hash[num]
else
tenths = num
num = num / 10
if num > 0
str += $hash[num*10] + " "
end
if (tenths-num*10) > 0
str += $hash[tenths-num*10]
end
end
end
str
end
end
decode = nil
puts "Enter 'decode x' replacing x with an integer between 1 and
999999999. Simply type 0 to finish:"
decode = gets.gsub(/[a-zA-Z]+\s/, '').to_i
puts decode.to_words
while (1..999999999).include?(decode)
puts "Enter 'decode x' replacing x with an integer between 1 and
999999999. Simply type 0 to finish:"
decode = gets.gsub(/[a-zA-Z]+\s/, '').to_i
puts decode.to_words
end
···
--
Posted via http://www.ruby-forum.com/.