“条件中的字符串文字"是什么意思?意思是? [英] What does "string literal in condition" mean?

查看:71
本文介绍了“条件中的字符串文字"是什么意思?意思是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我尝试运行该程序时,都会弹出一个错误消息,提示条件中的字符串文字(第10行)".我在做什么错了?

Whenever I try to run the program, an error pops up saying "string literal in condition (on line 10)". What am I doing wrong?

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的两侧指定完整条件.

You have to specify the full condition on both sides of the or.

if response == "a" or response == "A"

or的两侧未连接; Ruby不会根据左侧的内容对右侧的内容进行任何假设.如果右侧是裸字符串"A",那么,除了falsenil之外的任何内容都被视为"true",因此整个表达式始终都被计算为"true".但是Ruby注意到它是一个字符串,而不是一个布尔值,怀疑您可能没有指定要使用的含义,因此在问题中发出警告.

The two sides of the or are not connected; Ruby makes no assumptions about what's on the right based on what's on the left. If the right side is the bare string "A", well, anything other than false or nil is considered "true", so the whole expression evaluates as "true" all the time. But Ruby notices that it's a string and not actually a boolean value, suspects you might not have specified what you meant to, and so issues the warning in the question.

您还可以使用case表达式来简化对单个值的多次测试.如果您在单个when中提供多个可能性的列表,则将它们有效地or在一起:

You can also use a case expression to make it simpler to do multiple tests against a single value; if you supply a list of multiple possibilities in a single when, they are effectively ored together:

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

对于忽略字母大小写的特定情况,您还可以在测试之前将其转换为大写或小写:

For the specific situation of ignoring alphabetic case, you could also just convert to either upper or lower before testing:

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

这篇关于“条件中的字符串文字"是什么意思?意思是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆