我很难弄清楚为什么我的when
条件得不到满足。当move
分别包含"n"
,"s"
,"e"
或"w"
时,每个参数都应返回true。这是我的代码的简化版本:
loc = {x: 0, y: 0}
move = gets.chomp
case move
when move.match?(/n/); loc[:y] += move.gsub(/[^a-z]/, '').to_i
when move.match?(/s/); loc[:y] -= move.gsub(/[^a-z]/, '').to_i
when move.match?(/e/); loc[:x] += move.gsub(/[^a-z]/, '').to_i
when move.match?(/w/); loc[:x] -= move.gsub(/[^a-z]/, '').to_i
else; puts "Input '#{move}' not recognized!"
end
我也尝试使用move.include?('n')
等,但没有成功。
难道您不可以将代码简化成这样吗?
move = gets.chomp
case move
when /n/
puts "called #{move}" #add your stuff here
when /s/
puts "called #{move}"
when /e/
puts "called #{move}"
when /w/
puts "called #{move}"
else
puts "Input '#{move}' not recognized!"