我是红宝石的新手。我的过去是在 Java 中的。我正在尝试使用 switch case,在 Ruby 中显然被称为 case 表达式。我想接受用户输入,检查该输入以查看它是否包含某些字符,然后用其他字符替换这些字符。当我尝试运行这个简单的程序时,我得到了很多语法错误,但我不知道为什么。有人可以向我解释一下我是否错误地使用了这个语句,如果我什至可以在这种情况下使用 case 表达式?谢谢你。
empty_string = true
while empty_string do
print "Pleathe enter a thtring: "
user_input = gets.chomp
user_input.downcase!
case
when user_input.include? ("s")
user_input.gsub!(/s/, "th")
when user_input.include? ("ch")
user_input.gsub!(/ch/, "th")
when user_input == ""
puts "You typed noting! You get nothing sir!"
when user_input != ""
empty_string = false
else
puts "There are no 's's in your string."
end
end
puts "Zai jian, #{user_input}"
以下是与行和语法错误相关的错误
rb.rb:9 : 语法错误,意外(arg,当 user_input.include 时需要关键字_then 或 ',' 或 ';' 或 '\n'?("s")
rb.rb:11:语法错误,意外的keyword_when,当user_input.include 时期望keyword_end?("ch") ^
rb.rb:13 : 语法错误,意外的keyword_when,当user_input == "" ^ 时期望keyword_end
rb.rb:15:语法错误,意外keyword_when,当user_input != "" ^ rb.rb:17:语法错误,意外keyword_else,期待keyword_end
rb.rb:21:语法错误,意外的keyword_end,期待输入结束
下面是固定代码感谢@Phlip
empty_string = true
while empty_string do
print "Pleathe enter a thtring: "
user_input = gets.chomp
user_input.downcase!
case
when user_input.include?("s")
user_input.gsub!(/s/, "th")
empty_string = false
when user_input.include?("ch")
user_input.gsub!(/ch/, "th")
empty_string = false
when user_input == ""
puts "You typed noting! You get nothing sir!"
empty_string = true
else
puts "There are no 's's in your string."
end
end
puts "Zai jian, #{user_input}"
问题是我在 .include? 之后的空间,@Phlip 告诉我 Ruby 对空间敏感。我删除了空白区域并且它起作用了。之后我遇到了布尔值问题并修复了它。它现在按预期工作。