obj.nil? vs. obj == nil

前端 未结 7 804
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 22:08

Is it better to use obj.nil? or obj == nil and what are the benefits of both?

相关标签:
7条回答
  • 2020-11-29 22:49

    You can use Symbol#to_proc on nil?, whereas it wouldn't be practical on x == nil.

    arr = [1, 2, 3]
    arr.any?(&:nil?) # Can be done
    arr.any?{|x| x == nil} # More verbose, and I suspect is slower on Ruby 1.9.2
    ! arr.all? # Check if any values are nil or false
    
    0 讨论(0)
提交回复
热议问题