A concise explanation of nil v. empty v. blank in Ruby on Rails

A concise explanation of nil v. empty v. blank in Ruby on Rails

Asked on December 14, 2018 in Ruby on Rails.
Add Comment


  • 3 Answer(s)

    Try this simple solution,

    The keyword .nil? used any object  is true or  nil.  And .empty?   string it returns true.

    • String length == 0
    • Array length == 0
    • Hash length == 0

     when Running .empty? It will throw a NoMethodError. The .blank? comes in  implemented by Rails on any object  work like .empty? on string.

    nil.blank? == true
    false.blank? == true
    [].blank? == true
    {}.blank? == true
    "".blank? == true
    5.blank? == false
    0.blank? == false
    

    The .blank?  evaluates true on string.  And Rails also provides .present? .The returns  negation .blank?.

    "  ".blank? == true
    "  ".empty? == false
    

    Array gotcha: blank? will return false  if all elements  an array are blank in this case, use all? with blank?,

    Example:

    [ nil, '' ].blank? == false
    [ nil, '' ].all? &:blank? == true
    
    Answered on December 14, 2018.
    Add Comment

    Here is the simple code:  

     Any Expressions:  !obj.blank? == obj.present?

    Answered on December 14, 2018.
    Add Comment

    Explanation:

        Difference  .nil? and .empty? the methods are provided in  Ruby,  As .blank? is added in web development framework Rails.

    Answered on December 14, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.