When to use nil, blank, empty?
Ruby on-RailsRubyRuby on-Rails Problem Overview
Is there any guidelines on how to differentiate between .nil?
, .blank?
and .empty?
?
I'm generally always confused as to when to use them in my application as they all seem to mean the same thing but have different meanings.
Does anyone have any cheat sheet on the gory details?
Ruby on-Rails Solutions
Solution 1 - Ruby on-Rails
Here I made this useful table with all the cases
Solution 2 - Ruby on-Rails
-
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 fornil?
orempty?
.
Solution 3 - Ruby on-Rails
-
nil?
is defined on allObjects
, it only returnstrue
on thenil
singleton. -
blank?
is defined on all objects too, it returnstrue
if the object also responds toempty?
and is empty, or is afalse
type value (!object
is alwaystrue
). -
empty?
is defined on several collection objects, and istrue
if it has no elements. It is also defined onString
.
note that blank?
is ActiveSupport
and not in Rails 1.8.
Solution 4 - Ruby on-Rails
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.