So I have this hash below:
a_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",
"00" => "hundred", #not sure this is right
"000" => "thousand" #not sure this is right
}
Lets say my string input is “99100”.
Lets say I want my string output to be “ninty nine thousand one hundred”.
How do I go about using my hash above without typing each key/value. I was thinking maybe split my string at each char into an array….then for each number in that array return my value? Any other stratgies I should consider? This is what I have so far:
puts "test the hash! Type a number hit enter"
test_variable = gets.to_s.chomp
puts a_hash[test_variable]
Post some code so I can try out. Thanks!
Short answer: don’t do this yourself, find a library that does it for you.
However, it can be a cool exercise and it is actually an interesting problem. So, ignoring best practices of not reinventing the wheel… You’ll probably have to treat hundreds and thousands differently, because you can say “two hundred”, but “two seventy” doesn’t really make much sense.
Here’s my poorly-tested, unoptimised attempt. It is a proof-of-concept and I’m pretty sure I have overlooked many cases. If you want more help, try reading other people’s source code.
First we define two hashes, one for numbers, one for magnitudes (which are distinct because they can be prefixed with numbers in order to multiply them).
Next, define the conversion method.
To use it: