Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between .nil?, .blank? and .empty? [duplicate]

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

Can anyone tell me the difference between nil?, blank? and empty? in Ruby?

like image 590
Someth Victory Avatar asked Jun 14 '12 08:06

Someth Victory


People also ask

What is difference between empty and blank?

blank (adjective) - not written or printed on. empty (adjective) - containing nothing; not filled or occupied.

What is the difference between nil and empty in Ruby?

nil? is a standard method in Ruby that can be called on all objects and returns true for the nil object and false for anything else. empty? is a standard Ruby method on some objects like Arrays, Hashes and Strings.

Is nil empty Ruby?

Well, nil is a special Ruby object used to represent an “empty” or “default” value.

What is nil in Ruby on Rails?

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

In Ruby, nil in an object (a single instance of the class NilClass). This means that methods can be called on it. nil? is a standard method in Ruby that can be called on all objects and returns true for the nil object and false for anything else.

empty? is a standard Ruby method on some objects like Arrays, Hashes and Strings. Its exact behaviour will depend on the specific object, but typically it returns true if the object contains no elements.

blank? is not a standard Ruby method but is added to all objects by Rails and returns true for nil, false, empty, or a whitespace string.

Because empty? is not defined for all objects you would get a NoMethodError if you called empty? on nil so to avoid having to write things like if x.nil? || x.empty? Rails adds the blank? method.


After answering, I found an earlier question, "How to understand nil vs. empty vs. blank in Rails (and Ruby)", so you should check the answers to that too.

like image 179
mikej Avatar answered Sep 23 '22 03:09

mikej


Feel it ;)

NIL?

nil.nil? #=> true [].nil? #=> false "".nil? #=> false " ".nil? #=> false 

EMPTY?

[].empty? #=> true nil.empty? #=> undefined method "".empty? #=> true " ".empty? #=> false 

BLANK?

[].blank? #=> true nil.blank? #=> true "".blank? #=> true " ".blank? #=> true 
like image 42
fl00r Avatar answered Sep 21 '22 03:09

fl00r