【发布时间】:2017-01-16 10:11:10
【问题描述】:
有人分享了一些关于他们如何完成将数字转换为单词的挑战的 Ruby 代码。到目前为止,这个解决方案是最容易阅读的,但我并不完全理解它的递归方面。具体来说,在下面的行中......
elsif int.to_s.length == 1 && int/num > 0
return str + "#{name}"
如果 return 语句将代码从循环中中断,为什么这段代码不执行并在它为真时中断循环?例如,当 int = 4 且 num = 1 时,这将被证明为 true 并触发 return 语句,但代码会一直持续到 num = 4。
对代码的这方面的任何澄清,以及任何理解此解决方案的一般建议,都会有所帮助。仍在尝试理解递归。谢谢
def in_words(int)
numbers_to_name = {
1000000 => "million",
1000 => "thousand",
100 => "hundred",
90 => "ninety",
80 => "eighty",
70 => "seventy",
60 => "sixty",
50 => "fifty",
40 => "forty",
30 => "thirty",
20 => "twenty",
19=>"nineteen",
18=>"eighteen",
17=>"seventeen",
16=>"sixteen",
15=>"fifteen",
14=>"fourteen",
13=>"thirteen",
12=>"twelve",
11 => "eleven",
10 => "ten",
9 => "nine",
8 => "eight",
7 => "seven",
6 => "six",
5 => "five",
4 => "four",
3 => "three",
2 => "two",
1 => "one"
}
str = ""
numbers_to_name.each do |num, name|
if int == 0
return str
elsif int.to_s.length == 1 && int/num > 0
return str + "#{name}"
elsif int < 100 && int/num > 0
return str + "#{name}" if int%num == 0
return str + "#{name} " + in_words(int%num)
elsif int/num > 0
return str + in_words(int/num) + " #{name} " + in_words(int%num)
end
end
end
puts in_words(4) == "four"
puts in_words(27) == "twenty seven"
puts in_words(102) == "one hundred two"
puts in_words(38_079) == "thirty eight thousand seventy nine"
puts in_words(82102713) == "eighty two million one hundred two thousand seven hundred thirteen"
【问题讨论】: