Ruby:将数组项传递给case语句

我试图将数组传递给case语句,以便我可以将数组元素作为命令读取。 不幸的是,似乎它没有工作,程序跳转到else语句。

def input_console() quit = 0 puts "Tell me what you want to do:" loop do print "\n >>> " input = gets.chomp sentence = input.split case sentence when sentence[0] == "go" && sentence[1] == "to" puts sentence[2] when sentence[0] == "quit" quit = 1 else puts "No le entiendo Senor..." end break if quit == 1 end end 

无论你介绍什么,这段代码都会返回“No le entiendo Senor …”。 我希望在说“去哪里”之后得到我想去的地方。

拜托,¿你能帮我吗?

您可以通过使case语句独立于特定变量来实现此目的。

更改

 case sentence 

 case 

下面是一个示例,说明在检查数组中的值时如何使用case-when。

 numbers = [1,2,3] case when a[1] == 2 p "two" else p "nothing" end 

所以在你的情况下你可以说

 case when sentence[0] == "go" && sentence[1] == "to" puts sentence[2] when sentence[0] == "quit" quit = 1 else puts "No le entiendo Senor..." end 

你为什么要这个case陈述? (为什么quit Fixnum而不是布尔?实际上,为什么要使用它呢?)

 while true # ... prompt and get input ... if sentence[0] == "go" && sentence[1] == "to" puts sentence[2] elsif sentence[0] == "quit" break else puts "No le entiendo Senor..." end end 

你可以使用正则表达式。 像这样的东西:

 case gets when /\Ago to (.*)\Z/ puts $1 when /\Aquit\Z/ # handle quit else puts "No le entiendo Senor..." end 

\A匹配字符串的开头和\Z匹配在尾随换行符之前,因此您不需要chomp