每当我尝试运行程序时,就会出现错误,说"字符串在条件上(在第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"
,那么,除了false
或nil
以外的任何其他内容都被视为" 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"
是true
或false
。如果是true
,则条件将减少为
true or "A"
是
true
如果是false
,则该条件还原为
false or "A"
是
"A"
是真实,因为除了false
和nil
以外的所有内容都是真实的。
因此,无论 response
的内容如何,条件都将始终为真。
这就是警告警告您:字符串文字总是真实的,在条件下使用它们是没有意义的。
句法不是错误的;从某种意义上说,这是错误的。表达式response == "a" or "A"
被解释为(response == "a") or "A"
,由于"A"
,它总是真实的,因此将其放在条件下是没有用的。
if response == "a" or "A"
等于 if (response == "a") or "A"
。" a"是字符串的字面文字,这就是Ruby解释器抱怨的原因。