Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use nil, blank, empty? [duplicate]

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.

What is difference between empty and blank?

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

Is an empty array nil?

|| arr. empty? This will return true of array is empty or the array value is nil.

Is nil empty Ruby?

Well, nil is a special Ruby object used to represent an “empty” or “default” value. It's also a “falsy” value, meaning that it behaves like false when used in a conditional statement.


Here I made this useful table with all the casesenter image description here


  • nil? - checks to see if variable is referencing an object or not

  • empty? - may be used to check on various object types like empty string "" or empty array []

  • blank? - checks for nil? or empty?.


  • nil? is defined on all Objects, it only returns true on the nil singleton.

  • blank? is defined on all objects too, it returns true if the object also responds to empty? and is empty, or is a false type value (!object is always true).

  • empty? is defined on several collection objects, and is true if it has no elements. It is also defined on String.

note that blank? is ActiveSupport and not in Rails 1.8.


I found a good explanation here:

nil? tests whether the object is exactly nil, that is whether it is the one and only want instance of NilClass.

empty? is a method some objects respond to. You need to check the documentation for each case. For example, and empty array is one that is not nil (it is an array right?) and has no elements. An empty string is one that is not nil (it is a string right?) and has no bytes, nothing.

The blank? method you ask for does not belong to Ruby, it is a Rails extension: http://api.rubyonrails.com/classes/Object.html#M000011.

If you click through to the link at the end of that post you will find that the blank? method simply combines the nil? and empty? method calls.