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

前端 未结 18 1642
臣服心动
臣服心动 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:10
    if (discount||0) != 0
      #...
    end
    
    0 讨论(0)
  • 2020-12-22 16:12
    unless [nil, 0].include?(discount) 
      # ...
    end
    
    0 讨论(0)
  • 2020-12-22 16:16
    if discount.nil? || discount == 0
      [do something]
    end
    
    0 讨论(0)
  • 2020-12-22 16:20
    if discount and discount != 0
      ..
    end
    

    update, it will false for discount = false

    0 讨论(0)
  • 2020-12-22 16:23

    I prefer using a more cleaner approach :

    val.to_i.zero?
    

    val.to_i will return a 0 if val is a nil,

    after that, all we need to do is check whether the final value is a zero.

    0 讨论(0)
  • 2020-12-22 16:25

    When dealing with a database record, I like to initialize all empty values with 0, using the migration helper:

    add_column :products, :price, :integer, default: 0
    
    0 讨论(0)
提交回复
热议问题