如果答案始终为"y"
,我会使用这个因子应用无限期。
def continue?
answer = gets
if answer.downcase == "y"
main
elsif answer.downcase == "n"
exit
else
"This means n to me. Follow the rules next time. Bye."
end
end
def main
p "Enter any Integer"
out = gets
num = out.to_i
def factorial(num)
sum = num
(num-1).times {sum = sum * (num - 1); num = num-1}
sum
end
p factorial(num)
p "Do you want another number"
continue?
end
main
首先,#continue?在应用程序结束时,但是当我在#main中调用continue时,我不会因为不存在的方法而出错。那么,我动了#continue?到顶部,但现在我不能再调用#main,因为同样的方法错误。我可以把#continue?在#main方法中,但我不认为它会做很多事情。有没有更好的方法来处理这种情况?
如果我的代码关闭或我的练习不是最佳,请告诉我。我使用#inject作为阶乘,但我正在使用ruby 1.8.5所以我必须尽我所能。
答案 0 :(得分:3)
首先,从另一个函数调用main是很奇怪的,因为main只能在程序启动时调用一次。
其次,如果你以这种方式这样做,你将会因为你的callstack将继续增长而耗尽内存(main,continue,main continue,......)
为什么不让你继续?返回true或false值。然后在main中你可以写
begin
p "Enter any Integer"
out = gets
num = out.to_i
def factorial(num)
sum = num
(num-1).times {sum = sum * (num - 1); num = num-1}
sum
end
p factorial(num)
p "Do you want another number"
end while continue?
答案 1 :(得分:1)
您可以将条件放在while循环中,而不是每次都调用该函数。另外,请注意gets
方法,您应strip
输入。
def continue?
answer = gets.strip
if answer.downcase == "y"
true
elsif answer.downcase == "n"
false
else
p "This means n to me. Follow the rules next time. Bye."
false
end
end
def main
begin
p "Enter any Integer"
out = gets
num = out.to_i
def factorial(num)
sum = num
(num-1).times {sum = sum * (num - 1); num = num-1}
sum
end
p factorial(num)
p "Do you want another number"
end while continue?
end
main
答案 2 :(得分:0)
你有几个问题。首先,当你执行answer = gets
时,你得到的不仅仅是一封信,而是一个字母后面跟一个换行符,例如'y\n'
。解决方案是使用str#chomp。此外,当输入“y”或“n”以外的字母时,您实际上并未显示任何内容。这是固定的方法:
def continue?
answer = gets.chomp
if answer.downcase == "y"
main
elsif answer.downcase == "n"
exit
else
puts "This means n to me. Follow the rules next time. Bye."
end
end