Checking if a variable is not nil and not zero in ruby

前端 未结 18 1811
臣服心动
臣服心动 2020-12-22 15:38

I am using the following code to check if a variable is not nil and not zero

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

Is the

18条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-22 16:26

    You can take advantage of the NilClass provided #to_i method, which will return zero for nil values:

    unless discount.to_i.zero?
      # Code here
    end
    

    If discount can be fractional numbers, you can use #to_f instead, to prevent the number from being rounded to zero.

提交回复
热议问题