循环遍历Ruby中的case语句?
我试图确定循环一个case
语句的最佳方法,直到用户提供某个输入(在这种情况下, exit
)。
到目前为止,我的代码使用了一个while
循环,但是当我input = gets.chomp
遍地input = gets.chomp
时,它似乎有点多余。
这是一些缩写代码:
input = gets.chomp while input.downcase != 'exit' case input.downcase when 'help' puts "Available commands are..." input = gets.chomp #more when statements go here... else puts "That is not a valid command. Type 'HELP' for available commands." input = gets.chomp end end puts "Goodbye!"
我写的就像:
loop do input = gets.chomp.downcase case input when 'help' puts "Available commands are..." # more when statements go here... when 'exit' break else puts "That is not a valid command. Type 'HELP' for available commands." end end puts "Goodbye!"
loop
是针对这种情况设计的,你只想干净地循环,然后最终在某些条件下爆发。
为了最终清楚代码的作用,我会在读取输入后立即exit
,而不是嵌入在case
语句中。 这是一个小问题,但如果您正在编码而其他人必须帮助维护它,则有用!
loop do input = gets.chomp.downcase break if input == 'exit' case input when 'help' puts "Available commands are..." # more when statements go here... else puts "That is not a valid command. Type 'HELP' for available commands." end end puts "Goodbye!"
为什么不把while
改为:
while (input = gets.chomp.downcase) != 'exit'
请注意,这也意味着您可以使用case input
,而不是使用case input
。
编辑 :我在C的根源背叛了我……
正如评论中所提到的,这不是一个特别“ruby式”的解决方案。 当gets
返回nil
时,它还会导致堆栈跟踪。 您可能更喜欢将其拆分为两行:
while (input = gets) input = input.chomp.downcase break if input == 'exit' case input # when statements else puts "That is not a valid command. Type 'HELP' for available commands." end end
由于以下几个原因,我将“退出”与case
标准分开:
- 它是问题中循环逻辑的一部分,所以它(可以说)更具可读性,使其与其他情况分开。
- 我没有意识到Ruby
case
语句中的break
行为与我更熟悉的其他语言不同,所以我认为它不会做你想要的。
你也可以这样做:
while (input = gets) case input.chomp.downcase when 'exit' break # other when statements else puts "That is not a valid command. Type 'HELP' for available commands." end end
编辑 :我很高兴听到像Perl一样,Ruby也有$_
变量,将为其分配gets
的值:
while gets case $_.chomp.downcase when 'exit' break # other when statements else puts "That is not a valid command. Type 'HELP' for available commands." end end
您甚至可以通过使用break
退出循环来取消input
,而不是在while条件中检查结果
while true case gets.chomp.downcase when 'exit' break when 'help' # stuff else # other stuff end end