如果字符串包含子字符串,为什么我的条件不满足?

问题描述 投票:0回答:1

我很难弄清楚为什么我的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')等,但没有成功。

regex ruby switch-statement
1个回答
0
投票

难道您不可以将代码简化成这样吗?

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!"
© www.soinside.com 2019 - 2024. All rights reserved.