use*_*467 5 ruby string literals conditional-statements
每当我尝试运行程序时,会弹出一个错误,说"条件中的字符串文字(第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
Run Code Online (Sandbox Code Playgroud)
Mar*_*eed 17
你必须指定两侧的完整条件or.
if response == "a" or response == "A"
Run Code Online (Sandbox Code Playgroud)
两边or没有连接; Ruby根据左边的内容不做任何关于右边的假设.如果右边是裸字符串"A",那么,除了false或被nil认为是"真" 之外的任何东西,所以整个表达式始终评估为"真".但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
Run Code Online (Sandbox Code Playgroud)
对于忽略字母大小写的具体情况,您还可以在测试之前转换为上限或下限:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8302 次 |
| 最近记录: |