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

前端 未结 5 1001
萌比男神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 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.

提交回复
热议问题