Reputation: 995
I am trying to write a method that will take a number and return its string value. I am able to get everything in the hash to return. However, I am unable to get something like 43 to return. I thought initially about first checking to see if the argument had more than 1 integer... and maybe split them. I'm not sure. Anyone know how I would get numbers like 55,78,91 to be written out?
def into_word(int)
hash = {0 => "zero",
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 => "one hundred"
}
if hash.has_key?(int)
return hash[int]
# elsif int.to_s.length == 2
end
end
puts into_word(1)
puts into_word(2)
puts into_word(0)
puts into_word(4)
puts into_word(7)
puts into_word(9)
puts into_word(10)
puts into_word(42)
I am trying to do this without using any kind of gems.
Upvotes: 1
Views: 1114
Reputation: 1305
Rosetta Code has an algorithm that does exactly this, it works extremely well and can handle the stupidly large numbers as well.
Upvotes: 3
Reputation: 3396
Take a look at the humanize gem
https://github.com/radar/humanize
Upvotes: 2