“条件字符串文字”是什么意思?

每当我尝试运行程序时,会弹出一个错误,说“条件字符串文字(第10行)”。 我究竟做错了什么?

puts "Welcome to the best calculator there is. Would you like to (a) calculate the area of a geometric shape or (b) calculate the equation of a parabola? Please enter an 'a' or a 'b' to get started." response = gets.chomp if response == "a" or "A" puts "ok." elsif response == "b" or "B" puts "awesome." else puts "I'm sorry. I did not get that. Please try again." end 

您必须在or两侧指定完整条件。

 if response == "a" or response == "A" 

双方的or没有连接; Ruby根据左边的内容不做任何关于右边内容的假设。 如果右侧是裸字符串"A" ,那么除了falsenil之外的任何内容都被认为是“true”,因此整个表达式始终评估为“true”。 但Ruby注意到它是一个字符串而不是实际上是一个布尔值,怀疑你可能没有指定你的意思,因此在问题中发出警告。

您还可以使用case表达式来简化对单个值执行多个测试的过程。 如果你在一个单独的when提供多种可能性的列表,它们可以有效地or一起编辑:

 case response when "a","A" puts "ok" when "b","B" puts "awesome." else puts "I'm sorry. I did not get that. Please try again." end 

对于忽略字母大小写的具体情况,您还可以在测试之前转换为上限或下限:

 case response.upcase when "A" puts "ok" when "B" puts "awesome." else puts "I'm sorry, I did not get that. Please try again." end 

句法上没有错; 从某种意义上讲它是无用的,这是错误的。 表达式response == "a" or "A"被解释为(response == "a") or "A" ,由于"A"而总是如实,所以把它放在条件中是没用的。

if response == "a" or "A"等同于if (response == "a") or "A" 。 而“A”是一个字符串文字,这就是ruby翻译抱怨的原因。

这不是错误,这是一个警告。

你有条件

 response == "a" or "A" 

好吧, response == "a"true还是false 。 如果是,则条件减少到

 true or "A" 

是的

 true 

如果是false ,则条件减少到

 false or "A" 

是的

 "A" 

这是真实的 ,因为除了falsenil之外的一切都是真实的。

因此,无论response的内容如何,​​条件总是如此。

这就是警告警告你的内容:字符串文字总是很简单,在条件中使用它们是没有意义的。