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

前端 未结 18 1730
臣服心动
臣服心动 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:32

    From Ruby 2.3.0 onward, you can combine the safe navigation operator (&.) with Numeric#nonzero?. &. returns nil if the instance was nil and nonzero? - if the number was 0:

    if discount&.nonzero?
      # ...
    end
    

    Or postfix:

    do_something if discount&.nonzero?
    

提交回复
热议问题