如何比较 nil 和整数?

How can I compare a nil wth an integer?

对于 Ruby 2.4,我在 "if" 声明的一部分中有这个

row_data.index{|x| DataHelper.my_function(x) } > num_var

不幸的是,如果 "row_data.index{|x| DataHelper.my_function(x) }" 的计算结果为 nil,则上述语句会因错误而终止。有没有什么办法可以重写上面的内容,如果 "row_data.index{|x| DataHelper.my_function(x) }" 的计算结果为零,它会 return "false" ?我不想在我的 "if" 语句之前将表达式存储在变量中,因为如果执行没有到达那里,我可能甚至不需要执行该语句。感觉有单线,但不知道是什么。

您可以利用 nil.to_i 返回 0

if row_data.index{ |x| DataHelper.my_function(x) }.to_i > num_var
  # index is bigger than num_var
else
  # index is smaller or equal to num_var
end

根据 my_function 和 num_var 代表的内容,您可能还需要考虑 num_var == 0.

的情况

短路评估right way checking nil or false conditionals 有两个重要原因

  1. 简单的出路explicit conversionsto_sto_i等)可以让你暂时免于被加注exceptions/errors,但有时可以玩转恶魔打破你的条件你的一个比较值来自 - 0, "", [] 等等。因此,考虑到您的 代码在一段时间后可能不会持续足够长的时间,因此要特别小心。

    例如。 - 1

    if x.to_i > -1    
        puts x "is not a negative integer"
    else
        puts x "is a negative integer"
    end
    

    这可能很危险,因为 nil.to_i :=> 0if x.to_i > -1 逻辑检查中获得批准 进入带有转换值的条件块 0 万一nil.to_i)。

    可能您不会介意 ex。 - 1nil 打印为:0 is not a negative integer。这个怎么样?

    if x.to_i   
        puts " 1/x is" 1/x
    end
    

    它可以进一步提高每个 x 的 ZeroDivisionError: divided by 0nil,在这些情况下你要格外小心。可能您一开始就不想在您的街区内招待 nil

  2. 性能清洁代码 是您经常听到的两个流行语。 Short circuit evaluations (&&) 如果 前面的条件 false,则不要为 成功条件 而烦恼,这使得 条件执行得更快。此外,它会保护 nil 进入条件块的值并使其更容易受到攻击。

回答你的问题:

if (not row_data.index{|x| DataHelper.my_function(x) }.nil?) && (row_data.index{|x| DataHelper.my_function(x) } > num_var)
   # do your if block here
   # this keeps nil away
else
   puts "row_data.index{|x| DataHelper.my_function(x) } is nil"
end