问题
I am attempting to pass an array into a case statement so I can read the array elements as commands. Unfortunately, it seems that it is not working and the program jumps to the else statement.
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
This piece of code returns "No le entiendo Senor..." whatever you introduce. I expected to get the place I want to go after stating "go to Wherever".
Please, ¿may you help me?
回答1:
You can do this by making your case statement independent of a specific variable.
change
case sentence
to
case
回答2:
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
回答3:
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
回答4:
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
.
来源:https://stackoverflow.com/questions/20006056/ruby-passing-array-items-into-a-case-statement