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

Regex 如果字符串包含子字符串,为什么我的条件不满足?,regex,ruby,switch-statement,Regex,Ruby,Switch Statement,我很难弄清楚为什么我的条件没有得到满足。当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 m

我很难弄清楚为什么我的
条件没有得到满足。当
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!"
end
loc = {x: 0, y: 0}
puts 'make a move n s e w'
move = gets.chomp.downcase

unless move[/\A[n,s,e,w]\d+\z/]
  puts "Input '#{move}' not recognized! should start with n, s, e, w,"
end

move_distance = move[/\d+/].to_i

case move
when /^n/
  loc[:y] += move_distance
when /^s/
  loc[:y] -= move_distance
when /^e/
  loc[:x] += move_distance
when /^w/
  loc[:x] -= move_distance
else
  puts "Input '#{move}' not recognized!"
end

puts loc
只是一个关于你的gsub的旁注

move.gsub(/[^a-z]/, '').to_i
你不应该用吗

move.gsub(/[a-z]/, '').to_i

不确定您期望的输入数据是什么,但它应该是这样的吗

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!"
end
loc = {x: 0, y: 0}
puts 'make a move n s e w'
move = gets.chomp.downcase

unless move[/\A[n,s,e,w]\d+\z/]
  puts "Input '#{move}' not recognized! should start with n, s, e, w,"
end

move_distance = move[/\d+/].to_i

case move
when /^n/
  loc[:y] += move_distance
when /^s/
  loc[:y] -= move_distance
when /^e/
  loc[:x] += move_distance
when /^w/
  loc[:x] -= move_distance
else
  puts "Input '#{move}' not recognized!"
end

puts loc

您如何知道何时不满足条件?测试输入是什么?我认为Ruby的case接受正则表达式。您不需要调用match,只需使用/n/。测试输入类似于
2n
4sw
1e
,或
3s
。我相信这些条件没有得到满足,因为我的
else
代码正在执行。@G4145,“…case接受正则表达式。”是模糊的。Case语句使用方法
==
来确定
子句是否适用。这就是方法。例如,
/a/='cat'#=>true
,而
/a/=='dog'#=>false
。您需要
move.gsub(/[a-z]/,'')。to_i
等等
move.gsub(/[^a-z]/,“”)
删除所有数字,因此您将得到一个字母字符串,当转换为整数时,返回零。您可能希望将您在move.match?(/n/)
时更改的答案添加到
when/n/
中,这是此处的重要位。您可能还想添加为什么需要进行此更改。“难道你不能把代码简化成这样吗?”这不是最好的解释。谢谢,我不知道case语句接受regex。但是,我仍然不确定为什么
.match?
.include?
不起作用。另外,关于gsub,你是对的。接得好。@CarySwoveland是的!是打字错误,乐队也换了正则表达式,谢谢。