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

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

提交回复
热议问题