每当我尝试运行该程序时,都会弹出一条错误消息“条件字符串文字(第 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
最佳答案
您必须在 或
的两边指定完整的条件。
if response == "a" or response == "A"
或
的两端不相连; Ruby 不会根据左边的内容假设右边的内容。如果右侧是裸字符串 "A"
,那么,除了 false
或 nil
之外的任何内容都被视为“true”,因此整个expression 始终评估为“true”。但是 Ruby 注意到它是一个字符串而不是一个 bool 值,怀疑您可能没有指定您的意思,因此在问题中发出警告。
您还可以使用 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
关于ruby - "string literal in condition"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21556673/