【问题标题】:warning: string literal in condition警告:条件中的字符串文字
【发布时间】:2014-01-01 10:35:08
【问题描述】:

使用下面的第一段代码,我收到两条警告消息: warning: string literal in conditionx2

if input == "N" || "n"
  #do this
else input == "L" || "l"
  #do this

而不是使用不会导致警告的 this

if input == "N" || input == "n"
  #do this
else input == "L" || input == "l"
  #do this

我想知道为什么第一段代码会导致警告,以及使用它的缺点。

【问题讨论】:

  • input == "N" || "n" 表示 (input == "N") || "n" - ruby​​ 很有帮助并说“你做错了”

标签: ruby


【解决方案1】:

更改input == "N" || "n"

input == "N" || input == "n"

您还必须使用else if 而不是else

警告是说,您有一个字符串文字“n”,而不是布尔值或测试,它的计算结果始终为真。

【讨论】:

  • 不应该是elsif吗?
【解决方案2】:

我也在寻找这个问题的答案,感谢朋友找到了一些其他的解决方案。

1) 更改输入的大小写,因此您只需进行一次测试:

if input.downcase == "n"

2) 对输入数据使用更复杂的检查:

if %w{n N}.include?(input)     or
if ['n', 'N'].include?(input)

第二个让您的检查更加灵活,尤其是当您正在寻找一组条目时。

希望我的发现对其他人有所帮助。

【讨论】:

    【解决方案3】:

    我和你有同样的错误,但有不同的问题,通过谷歌发现这个问题不妨将我的解决方案发布给下一个谷歌人。

    我的代码中有一个错字,也给出了同样的警告:

    if input =! "N"
    

    当然是正确的方法:

    if input != "N"
    

    【讨论】:

    • 我有!==,因为=太多而给了我这个错误
    【解决方案4】:

    当你在写input == "N" || "n"( 内部Ruby 看到它(input == "N") || "n") 时,这意味着"n" 字符串对象总是一个真值。因为在Ruby 中每个对象都是true,除了nil 和@ 987654326@. Ruby 解释器被警告你没有必要把真值放在条件检查中。条件检查语句总是期望相等/不相等测试类型的表达式。现在你可以继续这种方式或重新考虑再次。 if input == "N" || input == "n" 没有发出任何警告,因为它遵守条件测试的规范。

    else input == "L" || "l" 是错误的,因为 else 语句不期望任何条件测试表达式。改成elseif input == "L" || "l"

    【讨论】:

      猜你喜欢
      • 2014-02-23
      • 2019-08-02
      • 1970-01-01
      • 1970-01-01
      • 2013-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多