每当我尝试运行该程序时,都会弹出一个错误,提示“字符串文字处于条件状态(第 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
or 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)