Ruby: passing array items into a case statement

喜夏-厌秋 提交于 2019-12-06 21:09:29

You can do this by making your case statement independent of a specific variable.

change

case sentence

to

case

Here is an example of how you would use case-when while checking for values in the array.

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

So in your case you can just say

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

Why are you making this a case statement? (And why is quit a Fixnum rather than a boolean? Actually, why have it at all?)

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

You could use regular expressions. Something like this:

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

\A matches the beginning of string and \Z matches just before the trailing newline, so you don't need chomp.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!