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

后端 未结 14 1107
被撕碎了的回忆
被撕碎了的回忆 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:42

    nil? is a standard Ruby method that can be called on all objects and returns true if the object is nil:

    b = nil
    b.nil? # => true
    

    empty? is a standard Ruby method that can be called on some objects such as Strings, Arrays and Hashes and returns true if these objects contain no element:

    a = []
    a.empty? # => true
    
    b = ["2","4"]
    b.empty? # => false
    

    empty? cannot be called on nil objects.

    blank? is a Rails method that can be called on nil objects as well as empty objects.

提交回复
热议问题