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

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

    0 讨论(0)
  • 2020-11-22 07:43

    • Everything that is nil? is blank?
    • Everything that is empty? is blank?
    • Nothing that is empty? is nil?
    • Nothing that is nil? is empty?

    tl;dr -- only use blank? & present? unless you want to distinguish between "" and " "

    0 讨论(0)
  • 2020-11-22 07:44

    I made this useful table with all the cases:

    enter image description here

    blank?, present? are provided by Rails.

    0 讨论(0)
  • 2020-11-22 07:44

    Rails 4

    an alternative to @corban-brook 's 'Array gotcha: blank?' for checking if an arrays only holds empty values and can be regarded as blank? true:

    [ nil, '' ].all? &:blank? == true
    

    one could also do:

    [nil, '', "", " ",' '].reject(&:blank?).blank? == true
    
    0 讨论(0)
  • 2020-11-22 07:45

    One difference is that .nil? and .empty? are methods that are provided by the programming language Ruby, whereas .blank? is something added by the web development framework Rails.

    0 讨论(0)
  • 2020-11-22 07:45

    Everybody else has explained well what is the difference.

    I would like to add in Ruby On Rails, it is better to use obj.blank? or obj.present? instead of obj.nil? or obj.empty?.

    obj.blank? handles all types nil, '', [], {}, and returns true if values are not available and returns false if values are available on any type of object.

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