How to understand nil vs. empty vs. blank in Ruby

后端 未结 14 1239
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 07:28

I find myself repeatedly looking for a clear definition of the differences of nil?, blank?, and empty? in Ruby on Rails. Here\'s the

14条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 07:58

    nil? can be used on any object. It determines if the object has any value or not, including 'blank' values.

    For example:

    example = nil
    example.nil?  # true
    
    "".nil?  # false
    

    Basically nil? will only ever return true if the object is in fact equal to 'nil'.

    empty? is only called on objects that are considered a collection. This includes things like strings (a collection of characters), hashes (a collection of key/value pairs) and arrays (a collection of arbitrary objects). empty? returns true is there are no items in the collection.

    For example:

    "".empty? # true
    "hi".empty?   # false
    {}.empty?  # true
    {"" => ""}.empty?   # false
    [].empty?   # true
    [nil].empty?  # false
    
    nil.empty?  # NoMethodError: undefined method `empty?' for nil:NilClass
    

    Notice that empty? can't be called on nil objects as nil objects are not a collection and it will raise an exception.

    Also notice that even if the items in a collection are blank, it does not mean a collection is empty.

    blank? is basically a combination of nil? and empty? It's useful for checking objects that you assume are collections, but could also be nil.

提交回复
热议问题