我无法弄清楚为什么我的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')
等,但未成功。
答案 0 :(得分:2)
难道您不可以将代码缩减为这样的内容吗?
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
关于您的gsub的一个补充说明
move.gsub(/[^a-z]/, '').to_i
您不应该使用吗?
move.gsub(/[a-z]/, '').to_i
答案 1 :(得分:1)
不确定要输入什么输入数据,但是应该是这样吗?
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