Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

  • blank? objects are false, empty, or a whitespace string. For example, "", " ", nil, [], and {} are blank.

  • nil? objects are instances of NilClass.

  • empty? objects are class-specific, and the definition varies from class to class. A string is empty if it has no characters, and an array is empty if it contains no items.

Is there anything missing, or a tighter comparison that can be made?

like image 492
Arrel Avatar asked May 19 '09 22:05

Arrel


People also ask

What is the difference between nil and empty in Ruby?

# nil? can be used on any Ruby object. It returns true only if the object is nil. # empty? can be used on some Ruby objects including Arrays, Hashes and Strings. It returns true only if the object's length is zero.

How do you know if a Ruby is nil?

In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).

What does nil mean in Ruby?

In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby's way of referring to nothing or void.


2 Answers

.nil? can be used on any object and is true if the object is nil.

.empty? can be used on strings, arrays and hashes and returns true if:

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

Running .empty? on something that is nil will throw a NoMethodError.

That is where .blank? comes in. It is implemented by Rails and will operate on any object as well as work like .empty? on strings, arrays and hashes.

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

.blank? also evaluates true on strings which are non-empty but contain only whitespace:

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

Rails also provides .present?, which returns the negation of .blank?.

Array gotcha: blank? will return false even if all elements of an array are blank. To determine blankness in this case, use all? with blank?, for example:

[ nil, '' ].blank? == false [ nil, '' ].all? &:blank? == true  
like image 190
Corban Brook Avatar answered Oct 12 '22 15:10

Corban Brook


I made this useful table with all the cases:

enter image description here

blank?, present? are provided by Rails.

like image 40
Julian Popov Avatar answered Oct 12 '22 15:10

Julian Popov