Ruby: “if !object.nil?” or “if object”

前端 未结 5 1000
萌比男神i
萌比男神i 2021-01-07 19:04

Are they the same when used in an if/else/end statement? What do you usually do? I\'m wondering if there are any subtle differences or edge cases where ob

相关标签:
5条回答
  • 2021-01-07 19:40

    Objects can override nil? but they cannot be falsely unless they are nil or false. Personally I use nil? or ActiveSupport's present? so that I maintain that flexibility. I also think it reads a bit better.

    0 讨论(0)
  • 2021-01-07 19:49

    if object tests if object isn't either nil or false.

    !object.nil? tests if object isn't nil. (Rubydoc)

    So when object is false, they have different values.

    0 讨论(0)
  • 2021-01-07 19:56

    There is one and only one case in which !object.nil? and object evaluate to different results in a boolean context and that is if object is false. In all other situations the result is the same.

    With this, I think we can answer your real question (which is: Is there any situation where I must use if !object.nil? instead of just if object when protecting against object being nil?):

    No, you can always use if object if you want to check against nil.

    0 讨论(0)
  • 2021-01-07 19:58

    Well. if object will behave differently from if !object.nil? if object=false.

    That's about it.

    0 讨论(0)
  • 2021-01-07 20:02

    There are differences. For example:

    false.nil?
    # => false
    

    So:

    if !false.nil?
      'foo'
    end
    # => "foo"
    
    if false
      'foo'
    end
    # => nil
    

    As @tokland suggested, in most cases using !obj.nil? construction is unnecessary.

    0 讨论(0)
提交回复
热议问题