每当我尝试运行该程序时,都会弹出一个错误消息,提示“条件中的字符串文字(第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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句