我使用下面的代码来检查一个变量是否不为零

if(discount != nil && discount != 0) 
  ...
end

还有更好的办法吗?


当前回答

def is_nil_and_zero(data)
     data.blank? || data == 0 
end  

如果我们传递""它将返回false,而空白?返回true。 当data = false时也是如此 空白的吗?对于nil、false、空或空白字符串返回true。 所以用空白更好吗?方法以避免空字符串。

其他回答

是的,我们有一条干净的红宝石路。

discount.to_f.zero?

这个检查处理了大量的情况,即折扣可能是nil,折扣可能是int 0,折扣可能是浮动0.0,折扣可能是字符串“0.0”,“0”。

另一种解决方案是使用Refinements,如下所示:

module Nothingness
  refine Numeric do
    alias_method :nothing?, :zero?
  end

  refine NilClass do
    alias_method :nothing?, :nil?
  end
end

using Nothingness

if discount.nothing?
  # do something
end

你可以利用NilClass提供的#to_i方法,它将为nil值返回零:

unless discount.to_i.zero?
  # Code here
end

如果折扣可以是小数,则可以使用#to_f来代替,以防止数字四舍五入为零。

unless discount.nil? || discount == 0
  # ...
end

在处理数据库记录时,我喜欢使用迁移帮助器将所有空值初始化为0:

add_column :products, :price, :integer, default: 0