ruby - "string literal in condition"是什么意思?

标签 ruby string conditional-statements literals

每当我尝试运行该程序时,都会弹出一条错误消息“条件字符串文字(第 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",那么,除了 falsenil 之外的任何内容都被视为“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/

相关文章:

python - 在 Python 列表中查找并替换为多个字符串值

javascript - 这些条件有什么不同?

ruby - 为什么 Mechanize HTML 内容打印 <!-- Session expired -->?

ruby - 如何在 Ruby 中传递变量?

string - haskell 问题 : io string -> [int]

vb.net - Len() 函数与 String.Length 属性;选择哪个?

string - 为什么从标准输入读取用户输入时我的字符串不匹配?

python - Pandas:条件聚合平均值和中位数

windows - 手动安装 Ruby 1.8.7(和其他东西)

ruby-on-rails - gem配置文件gemrc在ubuntu中的位置?它不在家里(~/.gemrc)或/etc/gemrc